我是Bootstrap中jQuery的新手,并做了一个w3school教程来为页面添加平滑滚动。只要锚点在同一页面上,这就可以正常工作。我添加了一个印记并希望在那里拥有相同的菜单,因此链接不指向另一个页面上的锚点(例如 home.html#section1(。
但这目前不起作用——单击链接根本没有任何效果。
脚本代码:
<script>
$(document).ready(function(){
// Add smooth scrolling to all links in navbar + footer link
$(".navbar a, footer a[href='#home']").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 (900) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 900, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
$(window).scroll(function() {
$(".slideanim").each(function(){
var pos = $(this).offset().top;
var winTop = $(window).scrollTop();
if (pos < winTop + 600) {
$(this).addClass("slide");
}
});
});
})
</script>
当我从印记页面中删除代码片段时,锚链接正在工作,但由于没有滚动,主页.html页面的动画部分不会加载(直到我手动滚动的那一刻,然后它们将加载(。感谢您的帮助!
假设
您只使用锚链接,请删除您的e.preventDefault()
。