Javascript 在URL上使用锚点平滑滚动
我试图在我的网站上使用平滑滚动,但我需要URL上的锚id,以提供浏览器后退按钮的功能。问题是:我需要在400毫秒之前显示#锚,但我不知道如何在脚本中调用该变量Javascript 在URL上使用锚点平滑滚动,javascript,anchor,smooth-scrolling,Javascript,Anchor,Smooth Scrolling,我试图在我的网站上使用平滑滚动,但我需要URL上的锚id,以提供浏览器后退按钮的功能。问题是:我需要在400毫秒之前显示#锚,但我不知道如何在脚本中调用该变量 $(document).ready(function(){ $('a[href*=#]').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.
$(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]'代码>更改url,但不要使用锚名称。如何更改?锚点存储在散列变量中,请参见示例并检查注释:
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 = _this.hash;
锚点的名称是什么?不幸的是,不仅仅是一个锚点,问题是每次我在这两个锚点之间滚动时都需要页面锚点。我查看了我的代码,在那里我做了相同的事情,并调整了您的代码以实现它,它对您有效吗?