页面高度不一样

问题描述 投票:0回答:1

我的项目有问题。我需要检测页面高度并将此高度作为参数添加到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 browser
1个回答
1
投票

这来自asynchroniouslyJavaScript行为。我想当你的脚本被执行时,一些元素还没有加载(并不总是) - 并且由于缺少元素,高度不同。

为了防止这种情况,您应该在加载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;
});
© www.soinside.com 2019 - 2024. All rights reserved.