DEMO FIDDLE
在点击锚和滚动时,需要为每个第一个div添加一个类,它是特定ID的子元素。
$(document).ready(function() {
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function() {
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
$(".box:first").addClass("black");
});
} // End if
});
});
#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;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<a href="#Segment1" class="">Segment1</a>
<a href="#Segment2" class="">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>
1条答案
按热度按时间tpxzln5u1#
这是我的建议。
1.将该类从所有
1.将类添加到属于散列的类
1.更改if以使代码更短/更简单