document.body为空或不是对象或者为什么获取不到document.documentElement.scrollHeight的值

当我们在<head></head>标记之间的script中,引用document.body时,会出现document.body为空或不是对象,这时可将js代码移至<body></body>标签之间,该问题即可解决。

 
 
下面说说将js代码放在<head></head>和<body></body>的区别:

放在head中的JS代码会在页面加载完成之前就读取,而放在body中的JS代码,会在整个页面加载完成之后读取。

那么有什么用途呢?

这就告诉我们,如果我们想定义一个全局对象,而这个对象是页面中的某个按钮(诸如此类)时,我们必须将其放入body中,道理很明显:如果放入head,那当你定义的时候,那个按钮都没有被加载,你能得到的只可能是一个undefind

同理,这也是为什么document.documentElement.scrollHeight 总是为0的原因,也是document.body 报错的原因

获取页面的高度:

function getPagearea(){
    if (document.compatMode == "BackCompat"){
      return {
         Math.max(document.body.scrollWidth,
                document.body.clientWidth),
        height: Math.max(document.body.scrollHeight,
                document.body.clientHeight)
      }
    } else {
      return {
         Math.max(document.documentElement.scrollWidth,
                document.documentElement.clientWidth),
        height: Math.max(document.documentElement.clientHeight,
                document.documentElement.scrollHeight)
      }
    }
  }

原文地址:https://www.cnblogs.com/xiamicomeon/p/4350803.html