【问题标题】:IE7/IE8 takes some time to return the correct scroll positionIE7/IE8 需要一些时间才能返回正确的滚动位置
【发布时间】:2012-04-18 14:59:10
【问题描述】:

为了显示一个对话框,我需要知道窗口的当前滚动位置。这是在 jQuery 的 $(document).ready 块中完成的。

然而,Internet Explorer 在必须记住滚动位置时会出错。

您可以通过在 IE 中打开以下 HTML 代码来尝试此操作,向下滚动一点并点击重新加载(对不起,我没有创建小提琴 - 因为滚动它在那里不起作用)。

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"     
type="text/javascript" charset="utf-8"></script>

<script type="text/javascript" charset="utf-8">
  $(document).ready(function() {
    alert(document.body.scrollTop);
    alert(document.body.scrollTop);
  });
</script>

<div style="height:4000px;">
</div>

第一个alert 显示0,第二个显示正确的数字。如果我使用setTimeout 并等待(在我的情况下)20 毫秒,它也可以在没有第一个警报的情况下工作 - 在其他情况下这可能需要另外的时间,因此不是解决方案。

我认为问题是IE首先滚动到顶部,做了一些事情,然后,过了一会儿,恢复了之前的滚动位置(可能它必须先渲染东西才能确保这个滚动位置仍然存在全部)。

有什么方法可以让浏览器立即滚动正确吗?

【问题讨论】:

  • 你能以某种方式排除 $().ready() 导致延迟吗?
  • 不,我不认为这会导致延迟,而是过早地调用/挂接:在调用 ready() 回调时,IE 似乎还没有完全准备好。
  • 您的 Web 应用程序的性能是否很慢?
  • 我不认为这是问题所在——试试上面的示例(性能应该不会很慢吧?)。

标签: javascript internet-explorer scroll restore scrolltop


【解决方案1】:

有几个属性可以让页面滚动,并且每个浏览器都不同。 这是我为接收正确滚动而编写的函数:

函数getScroll(类型) { 类型 = 类型 || '最佳'; 变量结果 = 0; 变量滚动 = 0; 如果(类型==='顶部') { if (ISQ.Http.browser.app !== 'ie' || ISQ.Http.browser.isIE9) 滚动 = window.pageYOffset; if (ISQ.Http.browser.app !== 'ie') scroll = returnMaxScroll(scroll, window.scrollY); scroll = returnMaxScroll(scroll, document.body.scrollTop); scroll = returnMaxScroll(scroll, document.documentElement.scrollTop); scroll = returnMaxScroll(scroll, document.body.parentNode.scrollTop); } else if (type === 'left') { if (ISQ.Http.browser.app !== 'ie' || ISQ.Http.browser.isIE9) 滚动 = window.pageXOffset; if (ISQ.Http.browser.app !== 'ie') scroll = returnMaxScroll(scroll, window.scrollX); scroll = returnMaxScroll(scroll, document.body.scrollLeft); scroll = returnMaxScroll(scroll, document.documentElement.scrollLeft); scroll = returnMaxScroll(scroll, document.body.parentNode.scrollLeft); } else if (type === '身高') { 开关(ISQ.Http.browser.app) { 案例“铬”: 案例“ff”: 案例“歌剧”: 案例“野生动物园”: // iframe 如果(window.top === 窗口) 滚动 = document.documentElement.scrollHeight; // 顶部窗户 别的 滚动 = document.body.scrollHeight; 休息; 默认: scroll = returnMaxScroll(scroll, document.body.scrollHeight); scroll = returnMaxScroll(scroll, document.documentElement.scrollHeight); scroll = returnMaxScroll(scroll, document.body.parentNode.scrollHeight); 休息; } } 否则如果(类型==='宽度') { scroll = returnMaxScroll(scroll, document.body.scrollWidth); scroll = returnMaxScroll(scroll, document.documentElement.scrollWidth); scroll = returnMaxScroll(scroll, document.body.parentNode.scrollWidth); } 返回滚动; } 函数 returnMaxScroll(value1, value2) { if (value1 > value2) 返回值1; 返回值2; } 仅供参考:您可能需要实现这些布尔值: - ISQ.Http.browser.app !== 'ie' - ISQ.Http.browser.isIE9

希望对你有帮助:)

【讨论】:

  • 非常感谢!我会尽快尝试的!
  • ie8的测试是什么?
猜你喜欢
  • 2014-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-16
  • 2018-09-10
  • 2020-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多