index.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. var className = 'gitbook-plugin-modal';
  2. require(['gitbook'], function (gitbook) {
  3. gitbook.events.bind('page.change', function () {
  4. // 配置项
  5. var cfg = gitbook.state.config.pluginsConfig.modal || {};
  6. var html = cfg.html;
  7. var closeable = cfg.closeable;
  8. var excludeUrls = cfg.excludeUrls || [];
  9. var shouldClose = false;
  10. var $modal;
  11. var $bookBody = window.document.getElementsByClassName('book-body')[0];
  12. function closeModal() {
  13. if ($modal) {
  14. $modal.remove();
  15. $modal = null;
  16. }
  17. shouldClose = true;
  18. }
  19. function showModal(content, closeable) {
  20. if ($bookBody.getElementsByClassName('gitbook-plugin-modal').length > 0) {
  21. $bookBody.getElementsByClassName('gitbook-plugin-modal')[0].style.display = 'block';
  22. return;
  23. }
  24. $modal = window.document.createElement('div');
  25. $modal.style.left = $bookBody.offsetLeft + 'px';
  26. $modal.style.width = $bookBody.clientWidth + 'px';
  27. $modal.className = className;
  28. $modal.innerHTML = '<div class="gitbook-plugin-modal-content">' + content + '</div>';
  29. $bookBody.appendChild($modal);
  30. if (closeable) {
  31. $modal.onclick = closeModal;
  32. }
  33. }
  34. function checkModal() {
  35. if (shouldClose) {
  36. return;
  37. }
  38. // URL 检查
  39. for (var i = 0; i < excludeUrls.length; i++) {
  40. var exReg = new RegExp(excludeUrls[i], 'g');
  41. if (exReg.test(decodeURI(window.location.href))) {
  42. return;
  43. }
  44. }
  45. showModal(html, closeable);
  46. }
  47. // 事件监听检查
  48. $bookBody.addEventListener('scroll', checkModal);
  49. var $bodyInner = window.document.getElementsByClassName('body-inner')[0];
  50. $bodyInner.addEventListener('scroll', checkModal);
  51. window.document.getElementById('book-search-input').getElementsByTagName('input')[0].addEventListener('input', closeModal);
  52. });
  53. });