为什么此代码同时使用“document.body”和“document.documentElement”?

0 html javascript

好的,所以我想弄清楚这个 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>
Run Code Online (Sandbox Code Playgroud)

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

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

document.body.scrollTop = 0;
Run Code Online (Sandbox Code Playgroud)

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

T.J*_*der 5

从问题标题预编辑:

document.body和 和有什么区别document.documentElement

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

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

因为不幸的是,当滚动主窗口的内容时,某些浏览器历史上会滚动html,而另一些浏览器则会滚动body。您可以在这里尝试您当前的浏览器:

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);
});
Run Code Online (Sandbox Code Playgroud)
.top {
  position: fixed;
  height: 2em;
  border-bottom: 1px solid #ddd;
  background: white;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)