Browse Source

:bug: outline id 不存在

Liyuan Li 5 years ago
parent
commit
204f2855f6
1 changed files with 8 additions and 5 deletions
  1. 8 5
      src/ts/markdown/outlineRender.ts

+ 8 - 5
src/ts/markdown/outlineRender.ts

@@ -21,10 +21,13 @@ export const outlineRender = (contentElement: HTMLElement, targetElement: Elemen
     targetElement.innerHTML = tocHTML;
     targetElement.querySelectorAll(".vditor-outline__item").forEach((item) => {
         item.addEventListener("click", (event: Event & { target: HTMLElement }) => {
-            const id = item.getAttribute("data-id");
+            const idElement = document.getElementById(item.getAttribute("data-id"));
+            if (!idElement) {
+                return;
+            }
             if (vditor) {
                 if (vditor.options.height === "auto") {
-                    let windowScrollY = document.getElementById(id).offsetTop + vditor.element.offsetTop;
+                    let windowScrollY = idElement.offsetTop + vditor.element.offsetTop;
                     if (!vditor.options.toolbarConfig.pin) {
                         windowScrollY += vditor.toolbar.element.offsetHeight;
                     }
@@ -34,13 +37,13 @@ export const outlineRender = (contentElement: HTMLElement, targetElement: Elemen
                         window.scrollTo(window.scrollX, vditor.element.offsetTop);
                     }
                     if (vditor.preview.element.contains(contentElement)) {
-                        contentElement.parentElement.scrollTop = document.getElementById(id).offsetTop;
+                        contentElement.parentElement.scrollTop = idElement.offsetTop;
                     } else {
-                        contentElement.scrollTop = document.getElementById(id).offsetTop;
+                        contentElement.scrollTop = idElement.offsetTop;
                     }
                 }
             } else {
-                window.scrollTo(window.scrollX, document.getElementById(id).offsetTop);
+                window.scrollTo(window.scrollX, idElement.offsetTop);
             }
             targetElement.querySelectorAll(".vditor-outline__item").forEach((subItem) => {
                 subItem.classList.remove("vditor-outline__item--current");