我有这样的URL:http://example.com#something如何删除#something,而不会导致页面刷新?
我尝试了以下解决方案:
window.location.hash = '';
Run Code Online (Sandbox Code Playgroud)
但是,这不会#从URL中删除哈希符号.
我的网站上有一个滑动面板.
完成动画后,我就像这样设置哈希
function() {
window.location.hash = id;
}
Run Code Online (Sandbox Code Playgroud)
(这是一个回调,并且id之前已分配).
这很好用,允许用户为面板添加书签,也可以使非JavaScript版本工作.
但是,当我更新哈希时,浏览器会跳转到该位置.我想这是预期的行为.
我的问题是:我该如何防止这种情况?即如何更改窗口的哈希值,但如果哈希存在则浏览器不会滚动到该元素?某种event.preventDefault()事情?
我正在使用jQuery 1.4和scrollTo插件.
非常感谢!
这是更改面板的代码.
$('#something a').click(function(event) {
event.preventDefault();
var link = $(this);
var id = link[0].hash;
$('#slider').scrollTo(id, 800, {
onAfter: function() {
link.parents('li').siblings().removeClass('active');
link.parent().addClass('active');
window.location.hash = id;
}
});
});
Run Code Online (Sandbox Code Playgroud) 纯javascript中的任何替代品?
以下适用于歌剧,铬和野生动物园.尚未在资源管理器上测试过:
http://monkey-me.herokuapp.com
https://github.com/coolcatDev/monkey-me-heroku/blob/master/static/js/myscripts.js
在页面加载时应向下滚动到div'.content':
var destiny = document.getElementsByClassName('content');
var destinyY = destiny[0].offsetTop;
scrollTo(document.body, destinyY, 200);
function scrollTo(element, to, duration) {
if (duration <= 0) return;
var difference = to - element.scrollTop;
var perTick = difference / duration * 2;
setTimeout(function() {
element.scrollTop = element.scrollTop + perTick;
scrollTo(element, to, duration - 2);
}, 10);
};
Run Code Online (Sandbox Code Playgroud) 为什么以下代码使滚动跳转到页面顶部?
window.location.hash = ''
Run Code Online (Sandbox Code Playgroud)
有没有办法在没有跳到页面顶部的情况下清空它?