【发布时间】:2017-05-27 17:28:02
【问题描述】:
$(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-hash。我无意中发现了一种修改它的方法,这样 URL 就不会更新(为“window.location.hash”添加了“none”),但是有一个问题;现在函数不会重复了。
会发生以下情况:
- 加载页面
- 向下滚动
- 按顶锚
- 页面滚动到顶部(不更新 url)
- 再次向下滚动
- 按顶锚
- 什么都没有发生
不知道我从哪里得到这个 sn-p,但我已经在我的 js 文件夹中有一段时间了。
【问题讨论】:
-
window.location.hash = none;- 如果您查看浏览器控制台,您会看到“none未定义”。如果您希望在单击<a href="#">top</a>链接时防止 URL 出现空哈希,请将id="top"添加到body或您的第一个/顶部元素或其他任何内容,然后将该链接更改为<a href="#top">top</a>
标签: javascript jquery html css