如何解决适用于移动设备但不适用于桌面设备的目录
一些上下文:这是一个博客的目录,但我希望桌面和移动设备中的 TOC 位于网站的不同部分。所以他们都有自己的 2 个不同的脚本。现在的问题是我设法让它的移动版本工作,但桌面似乎没有工作。有谁知道为什么?也许是代码冲突?
<!-- TOC -->
<script>
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
const id = entry.target.getAttribute("id");
if (entry.isIntersecting) {
document.querySelectorAll(".active").forEach((z) => {
z.classList.remove("active")
});
document.querySelector(`a[href="#${id}"]`).classList.add("active");
}
});
});
</script>
<script>
document.getElementById("content").querySelectorAll("h2,h3").forEach(function(heading,i) { // runs a function for all headings inside your rich text element
observer.observe(heading);
heading.setAttribute("id","toc-" + i); // gives each heading a unique id
const item = document.createElement("a"); // creates an <a> element called "item" for each heading
item.innerHTML = heading.innerHTML; // gives each item the text of the corresponding heading
("h2,h3").split(",").forEach(function(x) { // runs a function for each item in your headings list
if (heading.tagName.toLowerCase()==x) {
item.classList.add("tocitem","toc-" + x); // gives each item the correct class
}
});
item.setAttribute("href","#toc-" + i); // gives each item the correct anchor link
document.querySelector("#toc").appendChild(item); // places each item inside the Table of Contents div
});
</script>
<script>
document.getElementById("content").querySelectorAll("h2,"toc-mobile-" + i); // gives each heading a unique id
const item = document.createElement("a"); // creates an <a> element called "item" for each heading
item.innerHTML = heading.innerHTML; // gives each item the text of the corresponding heading
("h2,").forEach(function(x) { // runs a function for each item in your headings list
if (heading.tagName.toLowerCase()==x) {
item.classList.add("tocitem-mobile","toc-mobile-" + x); // gives each item the correct class
}
});
item.setAttribute("href","#toc-mobile-" + i); // gives each item the correct anchor link
document.querySelector("#toc-mobile").appendChild(item); // places each item inside the Table of Contents div
});
</script>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。