【发布时间】:2016-09-21 03:33:57
【问题描述】:
我试图让我的页面在单击 href 时滚动到特定的 <section>。我已经能够让页面跳转到我想要的<section>,但它并不流畅(就像我的 .animate 在 jQuery 中不起作用)。
HTML
<li><a href="#about" class="about-link">about us</a></li>
<section class="about" id="about">
<div class="container">
<h1>about us</h1>
<p>text</p>
</div>
</section>
jQuery
$(document).ready(function(){
// Add smooth scrolling to all links
$(".about-link").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;
});
} // End if
});
});
提前致谢!
【问题讨论】:
标签: jquery html scroll jquery-animate