[英]Smooth Scroll with Anchor on URL
我正在嘗試在我的網站上使用“平滑滾動”,但是我需要URL上的錨點ID,以提供瀏覽器“后退按鈕”的功能。 問題是:我需要在400 ms之前顯示#anchor,但是我不知道如何在腳本中調用該變量。
$(document).ready(function(){
$('a[href*=#]').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname) {
var $target = $(this.hash);
$target = $target.length && $target
|| $('[name=' + this.hash.slice(1) +']');
if ($target.length) {
var targetOffset = $target.offset().left;
$('html,body')
.animate({scrollLeft: targetOffset}, 400);
var timer = setTimeout(function() {
window.location.href = '#[anchor]';
}, 400);
return false;
}
}
});
});
window.location.href = '#[anchor]';
更改網址,但不要更改錨名稱。 我該如何改變?
錨存儲在hash
變量中,請參見示例並檢查注釋:
if (target.length) {
var _this = this; // first save the reference to 'this'
var targetOffset = $target.offset().left;
$('html,body').animate({scrollLeft: targetOffset}, 400);
var timer = setTimeout(function() {
window.location.href = _this.hash; // '_this.hash' contains the anchor
}, 400);
return false;
您也可以像這樣使用window.location.hash :
window.location.hash = _this.hash;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.