平滑滚动是指当用户点击页面内的链接时,页面不是立即跳转到目标位置,而是以动画效果逐渐滚动到目标位置,提供更好的用户体验。
使用jQuery实现平滑滚动到指定ID元素的基本方法如下:
// 方法1:使用animate()方法
$('html, body').animate({
scrollTop: $('#targetID').offset().top
}, 800); // 800毫秒的动画时间
<!DOCTYPE html>
<html>
<head>
<title>jQuery平滑滚动示例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.section {
height: 800px;
border-bottom: 1px solid #ccc;
padding: 20px;
}
.nav {
position: fixed;
top: 0;
left: 0;
background: #fff;
padding: 10px;
width: 100%;
}
</style>
</head>
<body>
<div class="nav">
<a href="#section1" class="scroll-link">章节1</a>
<a href="#section2" class="scroll-link">章节2</a>
<a href="#section3" class="scroll-link">章节3</a>
</div>
<div id="section1" class="section">
<h2>章节1</h2>
<p>这里是章节1的内容...</p>
</div>
<div id="section2" class="section">
<h2>章节2</h2>
<p>这里是章节2的内容...</p>
</div>
<div id="section3" class="section">
<h2>章节3</h2>
<p>这里是章节3的内容...</p>
</div>
<script>
$(document).ready(function() {
// 为所有带有scroll-link类的链接添加点击事件
$('.scroll-link').on('click', function(e) {
e.preventDefault(); // 阻止默认跳转行为
// 获取目标ID
var targetId = $(this).attr('href');
// 平滑滚动到目标元素
$('html, body').animate({
scrollTop: $(targetId).offset().top
}, 800); // 800毫秒的动画时间
});
});
</script>
</body>
</html>
var navHeight = $('.nav').outerHeight();
$('html, body').animate({
scrollTop: $(targetId).offset().top - navHeight
}, 800);
$('html, body').animate({
scrollTop: $(targetId).offset().top
}, {
duration: 800,
complete: function() {
console.log('滚动完成');
// 可以在这里添加滚动完成后的操作
}
});
$('html, body').animate({
scrollTop: $(targetId).offset().top
}, {
duration: 1000,
easing: 'swing' // 或使用'easeInOutQuad'等缓动函数
});
原因:可能是目标元素不存在或页面高度不足 解决:检查目标ID是否存在,确保页面内容足够长
原因:可能有固定定位的元素遮挡 解决:添加偏移量(如上方进阶实现1)
解决:在动画前停止当前动画
$('html, body').stop().animate({
scrollTop: $(targetId).offset().top
}, 800);
没有搜到相关的文章