Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[JS] document.documentElement与document.body #200

Open
david2tdw opened this issue Oct 15, 2020 · 3 comments
Open

[JS] document.documentElement与document.body #200

david2tdw opened this issue Oct 15, 2020 · 3 comments

Comments

@david2tdw
Copy link
Owner

No description provided.

@david2tdw
Copy link
Owner Author

document.documentElement与document.body

  • document代表的是整个文档(对于一个网页来说包括整个网页结构),document.documentElement是整个文档节点树的根节点,在网页中即html标签;
  • document.body是整个文档DOM节点树里的body节点,网页中即为body标签元素。

这两个属性主要是和html 的DTD有关

  • 在文档使用了DTD时,需要使用document.documentElement.scrollTop来获取滚动条滚过的长度 (document.body.scrollTop的值为0);
  • 在未使用DTD定义文档时,使用document.body.scrollTop获取值。

兼容性写法

    var top = document.documentElement.scrollTop || document.body.scrollTop;
    或
    var top = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;

漫谈document.documentElement与document.body

@david2tdw
Copy link
Owner Author

<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="utf-8" />
    <title>Javascript</title>
    <style>
      body {
        margin: 0;
        padding: 0;
        background: #ccc;
        font-size: 12px;
        overflow: auto;
      }
      .main {
        height: 900px;
        background-color: orange;
      }
    </style>
  </head>

  <body>
    <div class="main">
      
    </div>

    <script>
      window.onload = function () {
        window.addEventListener('scroll', function () {
          console.log(document.documentElement.scrollTop, document.body.scrollTop)
        })
      }
    </script>
  </body>
</html>

@david2tdw
Copy link
Owner Author

未声明DTD:

<!-- <!DOCTYPE html> -->
<html lang="zh-cn">
  <head>
    <meta charset="utf-8" />
    <title>Javascript</title>
    <style>
      body {
        margin: 0;
        padding: 0;
        background: #ccc;
        font-size: 12px;
        overflow: auto;
      }
      .main {
        height: 900px;
        background-color: orange;
      }
    </style>
  </head>

  <body>
    <div class="main">
      
    </div>

    <script>
      window.onload = function () {
        window.addEventListener('scroll', function () {
          console.log(document.documentElement.scrollTop, document.body.scrollTop)
        })
      }
    </script>
  </body>
</html>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant