我正在尝试使用摆动动画href
到我页面的某些部分。但是我不知道应该用什么来引用 HTML 的正确部分
。我认为最好的办法是选择我的 a
标签引用的 href id
。我对新方法持开放态度
jQuery:
$("li a").each(function() {
$(this).on("click", function() {
var mode = "swing";
$('html, body').animate({
scrollTop: $(/*HERE*/).offset().top
}, 750, mode);
});
})
HTML:
<div class="container">
<nav class="navbar navbar-default navbar-fixed-top">
<ul id="nav_pills" class="nav nav-pills" role="tablist">
<li role="presentation">
<a href="#about">About</a>
</li>
<li role="presentation">
<a id="test" href="#services">Services</a>
</li>
<li role="presentation">
<a href="#portfolio">Portfolio</a>
</li>
<li role="presentation">
<a href="#contact">Contact</a>
</li>
</ul>
</nav>
</div>
<!-- about -->
<section id="about">
<div class="border">
ABOUT
</div>
</section>
<!-- services -->
<section id="services">
<div class="border">
SERVICES
</div>
</section>
<!-- portfolio -->
<section id="portfolio">
<div class="border">
PORTFOLIO
</div>
</section>
<!-- contact -->
<section id="contact">
<div class="border">
CONTACT
</div>
</section>
最佳答案
工作演示: http://jsfiddle.net/p0tavns5/2/
$("li a").each(function() { // $('a[href^="#"]') might be a safer selector
$(this).on("click", function(e) {
var mode = "swing";
e.preventDefault(); //stop the default jump to fragment
$('html, body').animate({
scrollTop: $(this.hash).offset().top // .hash is the element's href
}, 750, mode);
});
})
来源:http://www.paulund.co.uk/smooth-scroll-to-internal-links-with-jquery
这还具有优雅降级的优点。如果它不运行(无脚本或其他),它将默认为常规片段链接。
关于javascript - 将动画摆动到页面的不同部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26914745/