Tho*_*ggi 88 javascript browser
如果您转到页面a并滚动然后刷新页面将在您离开它的位置刷新.这很好,但是这也发生在网址中有锚位置的网页上.例如,如果您点击链接http://example.com/post/244#comment5
并在环顾四周后刷新页面,则不会出现在锚点上并且页面会跳转.有没有办法用javascript来防止这种情况?所以无关紧要 - 你总是会导航到锚点.
jos*_*das 144
在Chrome上,即使您将scrollTop强制为0,它也会在第一次滚动事件后跳转.
你应该将滚动绑定到这个:
$(window).on('beforeunload', function() {
$(window).scrollTop(0);
});
Run Code Online (Sandbox Code Playgroud)
因此浏览器被欺骗以相信它在刷新之前就开始了.
imo*_*mos 59
要禁用自动滚动恢复,只需将此标记添加到head部分.
<script>history.scrollRestoration = "manual"</script>
Run Code Online (Sandbox Code Playgroud)
它不支持IE.浏览器兼容性
Jan*_*ela 18
经过多次失败后,我终于成功了.anzo在这里是正确的,因为beforeunload
当用户重新加载页面或点击链接时,使用会使页面跳转到顶部.这样unload
做的明显方法也是如此.
$(window).on('unload', function() {
$(window).scrollTop(0);
});
Run Code Online (Sandbox Code Playgroud)
Javascript方式(感谢ProfNandaa):
window.onunload = function(){ window.scrollTo(0,0); }
Run Code Online (Sandbox Code Playgroud)
编辑:16/07/2015
即使有unload
事件,Firefox仍然存在跳转问题.
mrt*_*man 16
由于浏览器行为的变化,不再推荐使用此解决方案.看到其他答案.
基本上,如果使用锚点,我们绑定到窗口滚动事件.想法是第一个滚动事件必须属于浏览器完成的自动重新定位.发生这种情况时,我们会自行重新定位,然后删除绑定事件.这可以防止后续页面滚动加密系统.
$(document).ready(function() {
if (window.location.hash) {
//bind to scroll function
$(document).scroll( function() {
var hash = window.location.hash
var hashName = hash.substring(1, hash.length);
var element;
//if element has this id then scroll to it
if ($(hash).length != 0) {
element = $(hash);
}
//catch cases of links that use anchor name
else if ($('a[name="' + hashName + '"]').length != 0)
{
//just use the first one in case there are multiples
element = $('a[name="' + hashName + '"]:first');
}
//if we have a target then go to it
if (element != undefined) {
window.scrollTo(0, element.position().top);
}
//unbind the scroll event
$(document).unbind("scroll");
});
}
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
83323 次 |
最近记录: |