我想做一個粘性目錄,當相應的標題滾動到它時,它的內容就會高亮顯示。當前的結構看起來像這樣
此圖像包含elementor中有兩列的部分。左列包含目錄,該列包含類& quot左列& quot并且使用Elementor Addon內容粘性插件使其具有粘性。 右列由標題組成,每個標題都有特定的id,并且是可滾動的,有一個類& quot右列& quot。 對于左邊的列,我使用HTML將所有內容條目的表格分組到一個類中。 目錄的HTML和CSS如下所示:
<div class="nav">
<h2 ><a href="#section-1">Section 1</a></h2>
<h2 ><a href="#section-2">Section 2</a></h2>
<h2 ><a href="#section-3">Section 3</a></h2>
</div>
<style>
.nav a:link {
display: block;
font-size: 14px!!important;
font-weight: normal;
margin-top: 8px;
margin-bottom: 8px;
text-decoration: none;
color: white;
text-align: right;
font-family: Work Sans;
}
.nav a.active {
color: black;
}
</style>
我使用了下面的javascript來應用突出顯示功能:
<script>
jQuery(document).ready(function($) {
// Select all headings in the right column
var sections = $('.right-column h1, .right-column h2, .right-column h3, .right-column h4, .right-column h5, .right-column h6');
// Select the table of contents section in the left column
var nav = $('.left-column .nav');
// Get the width of the left column
var navWidth = $('.left-column').outerWidth();
// Add an Intersection Observer to detect when a section is in view
var observer = new IntersectionObserver(function(entries) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
// Get the ID of the visible section
var sectionId = entry.target.getAttribute('id');
// Remove the "active" class from all table of contents links
nav.find('a').removeClass('active');
// Add the "active" class to the table of contents link that corresponds to the visible section
nav.find('a[href="#'+sectionId+'"]').addClass('active');
}
});
}, { threshold: 0.5 });
// Observe each section in the right column
sections.each(function() {
observer.observe(this);
});
// Adjust the offset value to account for the width of the left column
var offset = navWidth + 30; // Change the value of 30 as needed
// Add smooth scrolling to table of contents links
nav.find('a').click(function(e) {
e.preventDefault();
var target = $($(this).attr('href'));
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top - offset
}, 1000);}
});
});
</script>
問題是目錄沒有用黑色突出顯示,因為相應的標題顯示在右側。我不明白代碼在哪里出了問題。