[英]Disable default anchor jumping when clicking on a link
我搜索了幾個小時,終於找到了一個簡短的jQuery代碼,該代碼使我可以對錨鏈接的單擊進行動畫處理,但是當我單擊一個鏈接時,它會向下動畫,然后在沒有動畫的情況下跳至頂部100px,因為將哈希值賦予了動畫后的url,當您單擊它時會導致默認的錨鏈接行為。
我為您提供了一個代碼示例,並提供了一些修正意見,或者我認為這將是一個修復...
// Scroll.js (https://css-tricks.com/snippets/jquery/smooth-
scrolling/#comment-1635851)
/*
* Scroll.js:
* 1. added -100 after the .top property which reflects the navigation height.
*/
$(document).ready(function(){
// Add smooth scrolling to all links
$('a').on('click', function(e) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
e.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-100 // /* [1] */
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
只需在錨href屬性javascript::void(0)
上編寫即可
<a href="javascript:void(0)"></a>
雖然如果您希望它充當錨並具有網址...這將不起作用:(
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.