[英]Smooth Scroll with Anchor on URL
I'm trying to use Smooth Scroll on my site, but I need the anchor id on URL, to give the funcion of browser Back Button. 我正在尝试在我的网站上使用“平滑滚动”,但是我需要URL上的锚点ID,以提供浏览器“后退按钮”的功能。 The problem is: I need the #anchor to show up before 400 ms, but I don't know how can I call that variable in my script.
问题是:我需要在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;
}
}
});
});
The window.location.href = '#[anchor]';
window.location.href = '#[anchor]';
change the url but not with the anchor name. 更改网址,但不要更改锚名称。 How can I change that?
我该如何改变?
The anchor is stored in the hash
variable, see the example and check the comments: 锚存储在
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;
You can also use window.location.hash like this: 您也可以像这样使用window.location.hash :
window.location.hash = _this.hash;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.