[英]Top anchor with smooth scroll that won't repeat
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").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
}, 1000, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = none;
});
} // End if
});
});
我正在運行此程序以平滑滾動到“ #top”,而無需更改url哈希。 我無意中發現了一種修改方法,以使URL不會更新(“ window.location.hash”添加為“ none”),但是有一個問題。 現在該功能不再重復。
這是發生了什么:
不知道我在哪里得到這個片段,但是我已經在我的js文件夾中放了一段時間了。
您正在混合兩種滾動頁面的方式。
hash
是URL中的#something
...在滾動頁面加載時很有用。
請參閱此鏈接中的#hello
效果: https : #hello
然后,為使用戶滾動到頁面頂部,我將在鏈接的href
中使用頂部錨點的id
,以觸發滾動功能。
這將觸發此特定鏈接上的功能,而不是頁面中的所有鏈接。 ;)
最后,這一行: window.location.hash = none;
正在嘗試將原始的onload哈希值更改為none
,這將被解釋為未定義的變量,因為這需要一個字符串。
ReferenceError:沒有未定義
我只需刪除該行...
或者,如果您確實要清除哈希值:
window.location.hash = "";
工作滾動頂部功能: 有關更改的HTML標記,請參見codePen)
$(document).ready(function(){
// Add smooth scrolling to all links
$("a#backTOtop").on('click', function(event) {
console.log($(this).attr("href"));
// Make sure this.hash has a value before overriding default behavior
if ($(this).href !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var top = $(this).attr("href");
// 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: $(top).offset().top
}, 1000, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
// window.location.hash = none;
});
} // End if
});
});
如果不需要影響url哈希,只需刪除(或用//注釋)該行代碼即可; 因為它會在javascript中產生錯誤。
如果要從網址中刪除哈希,請嘗試以下代碼:
history.pushState('', document.title, window.location.pathname + window.location.search);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.