点击锚点滚动后为指定ID的首个子元素添加类
解决方法:点击锚点滚动后为对应区块的首个子元素添加指定类
问题出在原代码的选择器逻辑上:$(".box:first")会选取整个页面中第一个.box元素,不管点击的是哪个锚点,都会给同一个元素加类,完全没关联到当前锚点的目标区块。要实现需求,只需要调整选择器的作用范围:
- 在滚动完成的回调里,先移除所有已有的
.black类(避免多个元素同时高亮,优化交互体验) - 基于当前锚点对应的目标元素(
hash变量存储了锚点指向的ID),查找它下面的第一个.box元素,再添加类
修正后的JavaScript代码
$(document).ready(function() { // 为所有链接添加平滑滚动 $("a").on('click', function(event) { if (this.hash !== "") { event.preventDefault(); var hash = this.hash; $('html, body').animate({ scrollTop: $(hash).offset().top }, 800, function() { window.location.hash = hash; // 先清除之前的高亮,再给目标区块的首个.box添加类 $(".black").removeClass("black"); $(hash).find(".box:first").addClass("black"); }); } }); });
完整代码示例
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script> <a href="#Segment1">Segment1</a> <a href="#Segment2">Segment2</a> <br><br><br><br><br> <div id="Segment1"> <div class="box gray">Lorem Ipsum...</div> <div class="box gray">Lorem Ipsum...</div> <div class="box gray">Lorem Ipsum...</div> </div> <div id="Segment2"> <div class="box gray">Lorem Ipsum...</div> <div class="box gray">Lorem Ipsum...</div> <div class="box gray">Lorem Ipsum...</div> </div>
CSS
#Segment1 { background-color: yellow; padding: 50px; } #Segment2 { background-color: pink; padding: 50px; } .box { padding: 10px 20px; border: 1px solid #000000; margin-bottom: 5px; } .gray { background-color: lightgray; } .black { background-color: black; color: white; }
内容的提问来源于stack exchange,提问作者Adam Pablo
相关产品推荐
相关产品推荐

