jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。通过 jQuery,可以轻松地实现页面上的各种动态效果。
jQuery 的点击滚动到指定位置主要通过以下几种方式实现:
animate
方法:通过动画效果平滑滚动到指定位置。scrollTop
方法:直接滚动到指定位置。animate
方法<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Scroll Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#section1, #section2 {
height: 100vh;
border: 1px solid #000;
}
</style>
</head>
<body>
<a href="#" id="scrollToSection2">Scroll to Section 2</a>
<div id="section1">Section 1</div>
<div id="section2">Section 2</div>
<script>
$(document).ready(function() {
$('#scrollToSection2').click(function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $('#section2').offset().top
}, 1000); // 1000ms 动画时间
});
});
</script>
</body>
</html>
scrollTop
方法<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Scroll Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#section1, #section2 {
height: 100vh;
border: 1px solid #000;
}
</style>
</head>
<body>
<a href="#" id="scrollToSection2">Scroll to Section 2</a>
<div id="section1">Section 1</div>
<div id="section2">Section 2</div>
<script>
$(document).ready(function() {
$('#scrollToSection2').click(function(e) {
e.preventDefault();
$('html, body').scrollTop($('#section2').offset().top);
});
});
</script>
</body>
</html>
原因:
解决方法:
$(document).ready(function() {
$('#scrollToSection2').click(function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $('#section2').offset().top
}, 2000); // 增加动画时间到 2000ms
});
});
通过以上方法,可以解决点击链接后没有滚动到指定位置的问题。
领取专属 10元无门槛券
手把手带您无忧上云