尝试根据页面滚动位置突出显示侧边菜单。显示了很好的示例 here .
然而,当以不同的方式练习时,无法获得类似的滚动效果。代码是 here .
$('#sn').on('click', function(event) {
$(this).parent().find('a').removeClass('active');
$(this).addClass('active');
});
$(window).on('scroll', function() {
$('.target').each(function() {
if($(window).scrollTop() >= $(this).position().top) {
var id = $(this).attr('id');
$('#sn a').removeClass('active');
$('#sn a[href=#'+ id +']').addClass('active');
}
});
});
#sn {
width: 20%;
position: fixed;
}
#sn a {
display: block;
color: #000;
padding: 8px 16px;
text-decoration: none;
}
/* Change the link color on hover */
#sn a:hover {
background-color: #555;
color: white;
}
#sn .active {
background-color: #666;
color: rgb(58, 133, 204);
}
#sn .active:hover {
background-color: #4f5f;
color: rgb(235, 157, 13);
}
section {
height: 100vh;
overflow: auto;
background-color: #F7F7F7;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="sn" class="toggle_sn">
<a href="#abt_sec" class="item active">About</a>
<a href="#edu_sec" class="item">Education</a>
<a href="#soc_sec" class="item">Social</a>
</ul>
<section class="target" id="abt_sec">
ABOUT
</section>
<section class="target" id="edu_sec">
EDUCATION
</section>
<section class="target" id="soc_sec">
SOCIAL
</section>
我做错了什么?如何调试网页设计中的错误?这是jquery版本问题吗(比如是1.10.1,我的是3.3.1)?
最佳答案
1) 将 class="target"添加到您的部分。像这样:
<section id="abt_sec" class="target">ABOUT</section>
<section id="edu_sec" class="target">EDUCATION</section>
<section id="soc_sec" class="target">SOCIAL</section>
因为 jQuery 代码选择具有 target
class $('.target').each(function()
2) 更正最后一行语法:
来自这里:
$('#sn a[href=#'+ id +']').addClass('active');
为此:
$('#sn a[href="#'+ id +'"]').addClass('active');
因为 css 选择器的语法应该是:#sn a[href="#abt_sec"]
而不是:#sn a[href=#abt_sec]
。
这在您的情况下不起作用,因为 jQuery v3.3.1,如果您将工作示例中的 jQuery 版本从 jsFiddle 从 1.1 更改为 3.3.1,那么它也不会像您的示例一样出现相同的错误:
Uncaught Error: Syntax error, unrecognized expression: #sn a[href=#abt_sec]
所以你的代码应该是这样的:
$('#sn').on('click', function(event) {
$(this).parent().find('a').removeClass('active');
$(this).addClass('active');
});
$(window).on('scroll', function() {
$('.target').each(function() {
if($(window).scrollTop() >= $(this).position().top) {
var id = $(this).attr('id');
$('#sn a').removeClass('active');
$('#sn a[href="#'+ id +'"]').addClass('active');
}
});
});
用于查看其工作情况的代码笔:Codepen
关于javascript - 查找错误 : highlight side menu based on page scrolling position,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50106210/