在URL上使用锚点进行平滑滚动
Smooth Scroll with Anchor on URL
我试图在我的网站上使用平滑滚动,但我需要URL上的锚id,以提供浏览器返回按钮的功能。问题是:我需要#anchor在400ms之前出现,但我不知道如何在脚本中调用该变量。
$(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,但不会更改锚点名称。我该怎么改?
锚点存储在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;
相关文章:
- Safari(Mac OS)上的jQuery平滑滚动问题
- jquery平滑滚动问题
- javascript mootools平滑滚动'x'像素数量
- jQuery平滑滚动
- jQuery平滑滚动未滚动
- 更新Wordpress和我的平滑滚动停止工作
- 具有子菜单和平滑滚动的粘性导航
- 平滑滚动&懒惰
- 平滑滚动时更改 ID 的颜色
- 使用我的基于标签的平滑滚动脚本而不带“a”的解决方案
- 调整平滑滚动代码
- 使用 window.scrollBy) 平滑滚动
- 平滑滚动代码
- 如何在ng视图中进行页面渲染后的平滑滚动
- 如何使用requestAnimationFrame实现平滑滚动
- 如何由于浏览器的平滑滚动而忽略大量滚动事件
- 使用普通JavaScript平滑滚动到元素
- 平滑滚动并突出显示导航问题
- 在函数goToNext上平滑滚动+偏移
- 如何在HTML5页面上启用平滑滚动