我的项目有问题。我需要检测页面高度并将该高度作为参数添加到 url 中。运行良好。但是当我在浏览器中尝试并尝试刷新页面几次时,有时尺寸会比以前小一些。可以解决吗?
<script>
var body = document.body, html = document.documentElement;
var height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight) + 40;
document.location.href += "#" + height;
</script>
最佳答案
这来自 JavaScript
的异步
行为。我猜想当您的脚本执行时,某些元素尚未加载(并非总是如此) - 并且由于缺少元素,高度有所不同。
为了防止这种情况,您应该在加载 document
后执行代码。
(function() {
var body = document.body, html = document.documentElement;
var height = Math.max(body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight) + 40;
document.location.href += "#" + height;
})();
或使用 jQuery:
$( document ).ready(function() {
var body = document.body, html = document.documentElement;
var height = Math.max(body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight) + 40;
document.location.href += "#" + height;
});
关于javascript - 页面高度仍然不一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49110360/