window.scrollTo 在 Safari 中异步工作吗? [英] Does window.scrollTo work asynchronously in Safari?

查看:64
本文介绍了window.scrollTo 在 Safari 中异步工作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我发现 Safari(6.0.5 (8536.30.1)、MacOS 10.8.4)中的 window.scrollTo 行为非常奇怪(在我看来).它似乎是异步工作的.

Recently I found very strange(in my opinion) window.scrollTo behaviour in Safari(6.0.5 (8536.30.1), MacOS 10.8.4). It seems it works asynchronously.

我的任务听起来像:

  • 使一些绝对定位的 div 固定(固定)
  • 做一些页面滚动
  • 使之前修改的 div 绝对定位回来(取消固定)

所以要取消固定这个 div,我必须在滚动修改完成后立即执行取消固定例程.在这里我遇到了问题.除了 Safari,我检查过的每个浏览器都正确.

So to unpin this div I have to execute unpin routine just after scroll modification is complete. And here I met the problem. Every browser I checked does it correctly except Safari.

重现步骤:

  1. 在 Safari 中打开任何网页,并确保它至少可以滚动 100 像素,并且初始滚动偏移为 0
  2. 在开发工具中打开 js 控制台
  3. 执行:window.scrollTo(0, 100);console.log(document.body.scrollTop);

输出为 0.但是当我将此代码更改为 window.scrollTo(0, 100);window.setTimeout(function() {console.log(document.body.scrollTop)}, 1); 输出为 100,符合预期.

The output is 0. But when I change this code to window.scrollTo(0, 100); window.setTimeout(function() {console.log(document.body.scrollTop)}, 1); the output is 100, as expected.

以下是我测试过的所有其他浏览器(可以正常工作):

Here are all other browsers I've tested(where it works fine):

  • Chrome 27.0.1453.110 (MacOS 10.8.4)
  • Firefox 21.0 (MacOS 10.8.4)
  • Opera 12.15 b1748 (MacOS 10.8.4)
  • IE 8.0.7601.17514 (Win7)

好吧,只要我的代码示例不是跨浏览器,就可以更轻松地使用 jQuery 在任何网页上检查此行为:

Well, as soon as my code sample is not cross browser, it's easier to check this behaviour on any web page with jQuery:

var $w = $(window); 
$w.scrollTop(100); 
console.log($w.scrollTop());

VS

var $w = $(window); 
$w.scrollTop(100); 
window.setTimeout(function() {
    console.log($w.scrollTop())
}, 1);

这种行为是正常的还是一个错误?如何处理?(现在我修改了 $.fn.scrollTop 以返回 $.Deferred 而不是链接并在除 Safari 之外的所有浏览器的主线程中立即解析).

Is this behavior is ok or is it a bug? How to handle it? (Now I modified $.fn.scrollTop to return $.Deferred instead of chaining and resolve it instantly in main thread in all browsers except Safari).

推荐答案

requestAnimationFrame 中设置滚动顶部实际上解决了我在浏览器中的问题.

Setting scroll top in requestAnimationFrame actually solved my issue in browsers.

这篇关于window.scrollTo 在 Safari 中异步工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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