阻止浏览器在HTML5 History popstate上滚动 [英] Prevent browser scroll on HTML5 History popstate

查看:391
本文介绍了阻止浏览器在HTML5 History popstate上滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能防止发生popstate事件时滚动文档的默认行为?

我们的站点使用jQuery动画滚动和History.js,并且状态更改应该通过pushstate或popstate滚动用户到页面的不同区域。麻烦的是浏览器在popstate事件发生时自动恢复前一状态的滚动位置。



我试过使用容器元素设置为100%宽度和高度并滚动该容器内的内容。我发现的问题是,它看起来没有滚动文档那么顺利。特别是如果使用很多css3像框阴影和渐变。



我也尝试在用户启动的滚动过程中存储文档的滚动位置并在浏览器滚动后恢复它该页面(在popstate上)。这在Firefox 12中运行正常,但在Chrome 19中,由于页面正在滚动和恢复,因此闪烁。我假设这是在滚动和滚动事件被触发之间的延迟(滚动位置被恢复)。

Firefox滚动页面(并且触发滚动事件)在popstate触发之前,Chrome首先触发popstate然后滚动文档。



我见过的所有使用历史API的网站都使用类似于那些的解决方案当用户前进/前进时(例如GitHub),上面或者忽略滚动位置的变化。



是否可以阻止文件在popstate事件中滚动?

解决方案

  if('scrollRestoration'in history){
history.scrollRestoration ='手动';

由Google于2015年9月2日发布) b
浏览器支持:支持(自46以来)



Firefox:将于4月19日开始支持,2016(46.0版)

IE / Edge: 寻求支持 (然后在评论中留下链接)



Opera:支持(自33以来)



有关MDN的更多信息。


Is it possible to prevent the default behaviour of scrolling the document when a popstate event occurs?

Our site uses jQuery animated scrolling and History.js, and state changes should scroll the user around to different areas of the page whether via pushstate or popstate. The trouble is the browser restores the scroll position of the previous state automatically when a popstate event occurs.

I've tried using a container element set to 100% width and height of the document and scrolling the content inside that container. The problem with that I've found is it doesn't seem to be nearly as smooth as scrolling the document; especially if using lots of css3 like box-shadows and gradients.

I've also tried storing the document's scroll position during a user initiated scroll and restoring it after the browser scrolls the page (on popstate). This works fine in Firefox 12 but in Chrome 19 there is a flicker due to the page being scrolled and restored. I assume this is to do with a delay between the scroll and the scroll event being fired (where the scroll position is restored).

Firefox scrolls the page (and fires the scroll event) before popstate fires and Chrome fires popstate first then scrolls the document.

All the sites I've seen that use the history API either use a solution similar to those above or just ignore the scroll position change when a user goes back/forward (e.g. GitHub).

Is it possible to prevent the document being scrolled at all on popstate events?

解决方案

if ('scrollRestoration' in history) {
  history.scrollRestoration = 'manual';
}

(Announced by Google on September 2, 2015)

Browser support:

Chrome: supported (since 46)

Firefox: will be supported from April 19, 2016 (version 46.0)

IE/Edge: ask for support (then leave link in comment)

Opera: supported (since 33)

More info on MDN.

这篇关于阻止浏览器在HTML5 History popstate上滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆