需要单页网站的给定代码进行平滑滚动,使用标签可以正常工作,但效果不平滑。
$('ul.nav-main').find('a').click(function() {
var $href = $(this).attr('href');
var $anchor = $('#' + $href).offset();
window.scrollTo($anchor.left, $anchor.top);
return false;
});
ul {
list-style: none;
margin-bottom: 100px;
}
li {
padding: 5px 15px;
}
div {
height: 500px;
margin-bottom: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a href="#div1">Div 1</a></li>
<li><a href="#div2">Div 2</a></li>
<li><a href="#div3">Div 3</a></li>
</ul>
<div id="div1" style="background: red;">
Div 1
</div>
<div id="div2" style="background: green;">
Div 2
</div>
<div id="div3" style="background: blue;">
Div 3
</div>
答案 0 :(得分:0)
尝试
$(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;
});
}
});
});
ul {
list-style: none;
margin-bottom: 100px;
}
li {
padding: 5px 15px;
}
div {
height: 500px;
margin-bottom: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li><a href="#div1">Div 1</a></li>
<li><a href="#div2">Div 2</a></li>
<li><a href="#div3">Div 3</a></li>
</ul>
<div id="div1" style="background: red;">
Div 1
</div>
<div id="div2" style="background: green;">
Div 2
</div>
<div id="div3" style="background: blue;">
Div 3
</div>