为了显示对话框,我需要知道窗口的当前滚动位置。这是在 jQuery 的 $(document).ready
block 中完成的。
但是,Internet Explorer 在必须记住滚动位置时会破坏一些东西。
您可以通过在 IE 中打开以下 HTML 代码来尝试此操作,向下滚动一点并点击重新加载(抱歉,我没有创建 fiddle - 因为滚动它在那里不起作用)。
<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 首先滚动到顶部,做了一些事情,然后过了一会儿,恢复了以前的滚动位置(可能它必须先渲染东西以确保这个滚动位置仍然存在于全部)。
有什么合适的方法可以让浏览器立即正确滚动吗?
最佳答案
有几个属性可以让页面滚动,每个浏览器都不一样。 这是我为了接收正确的滚动而编写的函数:
function getScroll(type) { type = type || 'top'; var result = 0; var scroll = 0; if (type === 'top') { if (ISQ.Http.browser.app !== 'ie' || ISQ.Http.browser.isIE9) scroll = 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) scroll = 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 === 'height') { switch (ISQ.Http.browser.app) { case "chrome": case "ff": case "opera": case "safari": // iframe if (window.top === window) scroll = document.documentElement.scrollHeight; // top window else scroll = document.body.scrollHeight; break; default: scroll = returnMaxScroll(scroll, document.body.scrollHeight); scroll = returnMaxScroll(scroll, document.documentElement.scrollHeight); scroll = returnMaxScroll(scroll, document.body.parentNode.scrollHeight); break; } } else if (type === 'width') { scroll = returnMaxScroll(scroll, document.body.scrollWidth); scroll = returnMaxScroll(scroll, document.documentElement.scrollWidth); scroll = returnMaxScroll(scroll, document.body.parentNode.scrollWidth); } return scroll; } function returnMaxScroll(value1, value2) { if (value1 > value2) return value1; return value2; }
FYI: you may need to implement these booleans: - ISQ.Http.browser.app !== 'ie' - ISQ.Http.browser.isIE9
希望对你有帮助:)
关于javascript - IE7/IE8 需要一些时间才能返回正确的滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10212164/