为什么这段代码同时使用`document.body`和`document.documentElement`?

时间:2018-02-27 17:00:48

标签: javascript html

好的,所以我试图弄清楚这个JS代码是如何工作的。你能解释一下这些东西吗?

有代码(我已经复制了一些w3schools'代码,完整:https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_scroll_to_top

<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>

<script>
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {scrollFunction()};

function scrollFunction() {
    if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
        document.getElementById("myBtn").style.display = "block";
    } else {
        document.getElementById("myBtn").style.display = "none";
    }
}

function topFunction() {
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
}
</script>

我认为document.documentElement意味着它是一个HTML,它包含页面上的所有元素。我错了吗?

那么为什么我们需要topFunction()中的两个变量设置?当我删除这一行时:

document.body.scrollTop = 0;

一切仍然有效,为什么我们需要这部分代码呢?谢谢。

1 个答案:

答案 0 :(得分:4)

从问题标题预编辑:

  

document.bodydocument.documentElement之间的区别是什么?

document.bodybody元素。 document.documentElement是(在HTML文档中)html元素。

  

那么为什么我们需要topFunction()中的两个变量设置?

因为不幸的是,在滚动主窗口的内容时,某些浏览器历来滚动html,其他浏览器body。您可以在此处尝试当前的浏览器:

&#13;
&#13;
var n, div;
for (n = 1; n <= 100; ++n) {
  div = document.createElement('div');
  div.innerHTML = String(n);
  document.body.appendChild(div);
}
var bodyDisplay = document.getElementById("body-display");
var docElDisplay = document.getElementById("docel-display");

document.addEventListener("scroll", function() {
  bodyDisplay.innerHTML = String(document.body.scrollTop);
  docElDisplay.innerHTML = String(document.documentElement.scrollTop);
});
&#13;
.top {
  position: fixed;
  height: 2em;
  border-bottom: 1px solid #ddd;
  background: white;
}
&#13;
<div class="top">
  <div>
    body scrollTop:
    <span id="body-display"></span>
  </div>
  <div>
    documentElement scrollTop:
    <span id="docel-display"></span>
  </div>
</div>
<div>Scroll up and down</div>
&#13;
&#13;
&#13;