抱歉,您的浏览器无法访问本站

本页面需要浏览器支持(启用)JavaScript


了解详情 >

富文本编辑器中的标签联想实现

最近在仿浮墨笔记 flomo 学习,碰到在富文本编辑器中展示已有的标签 tag,苦恼于如何定位光标输入位置,直到看见大神的代码,恍然大悟。

const navItems = document.querySelectorAll(".toc li"); if (!navItems.length) return; const sections = [...navItems].map((element) => { const link = element.querySelector(".toc-link"); const target = document.getElementById( decodeURI(link.getAttribute("href")).replace("#", "") ); link.addEventListener("click", (event) => { event.preventDefault(); window.scrollTo({ top: target.offsetTop + 100, behavior: "smooth" }); }); return target; }); function activateNavByIndex(target) { if (target.classList.contains("active-current")) return; document.querySelectorAll(".toc .active").forEach((element) => { element.classList.remove("active", "active-current"); }); target.classList.add("active", "active-current"); let parent = target.parentNode; while (!parent.matches(".toc")) { if (parent.matches("li")) parent.classList.add("active"); parent = parent.parentNode; } } function findIndex(entries) { let index = 0; let entry = entries[index]; if (entry.boundingClientRect.top > 0) { index = sections.indexOf(entry.target); return index === 0 ? 0 : index - 1; } for (; index < entries.length; index++) { if (entries[index].boundingClientRect.top <= 0) { entry = entries[index]; } else { return sections.indexOf(entry.target); } } return sections.indexOf(entry.target); } function createIntersectionObserver(marginTop) { marginTop = Math.floor(marginTop + 10000); let intersectionObserver = new IntersectionObserver( (entries, observe) => { let scrollHeight = document.documentElement.scrollHeight + 100; if (scrollHeight > marginTop) { observe.disconnect(); createIntersectionObserver(scrollHeight); return; } let index = findIndex(entries); activateNavByIndex(navItems[index]); }, { rootMargin: marginTop + "px 0px -100% 0px", threshold: 0, } ); sections.forEach((element) => { element && intersectionObserver.observe(element); }); } createIntersectionObserver(document.documentElement.scrollHeight); } document.addEventListener("DOMContentLoaded", listennSidebarTOC); document.addEventListener("pjax:success", listennSidebarTOC);