javascript - HTML:谁负责显示/隐藏滚动条?

标签 javascript jquery html css

我读了一些网上文章,他们说 html 标签代表浏览器窗口,因此 html 等于浏览器窗口大小。如果 body 尺寸大于 html 尺寸,则会显示滚动条。所以是 html 元素控制是否显示滚动条。

就像这张图一样:

enter image description here

你可能会这样想:

html { overflow: auto; }

所以如果想故意隐藏滚动条,我会这样做:

// myCSS.css
html { overflow: hidden;// override default }

如果我想滚动到正文的某个位置:

var position = 500;
$('html').animate({scrollTop: position}, 1000);

这听起来很有希望。但我使用FireBug检查html标签的高度,它们总是大于或等于body的大小。 (假设默认网页没有CSS,并且body中的内容超出了窗口大小)html标签的大小实际上并不是浏览器窗口的大小,它更多的是body的大小 元素。

那么滚动条到底是从哪里来的呢?滚动条到底是如何工作的?

最佳答案

I read some online articles and they say that html tag represent the browser window, so html is equals to the browser window size. If the body size is greater than the html size, then the scrollbar will show up. So it is the html element that controls to display the scrollbar or not.

这确实是非常错误的。

什么是CSS 2.1 Spec section 9.1.1说是

When the viewport is smaller than the area of the canvas on which the document is rendered, the user agent should offer a scrolling mechanism.

但这似乎也不太正确,因为通常不提供滚动来将视口(viewport)移动到具有负 x 或负 y 值的 Canvas 区域,即使内容绘制在那里。

我能确定的最好情况是,滚动条可用于在 Canvas 区域上移动视口(viewport),这些区域具有 0 或正 x 和 y 坐标的渲染框。

无论如何,html 元素框和 body 元素框的大小都不是特殊的。它们只是 Canvas 上渲染的框,与其他元素相同。由于溢出或绝对定位,其他元素可能会呈现在这些框之外,并且滚动机制将考虑这些元素的完整大小。

示例和图表可能有助于理解。考虑这个例子:

<!DOCTYPE html>
<html>
  <head>
    <title>Scroll limits</title>
    <style>
      html { padding:20px; border:1px green solid; height:80px; }
      body { margin:0; border:1px black solid; height:150px; }
      #div1 { position:absolute; top:-50px; height:65px; left:-50px; 
              width: 65px; background-color:blue; }
      #div2 { position:absolute; top:200px; height:65px; left: 110%; 
              width: 65px; background-color:yellow; }
    </style>
  </head>
  <body>
    body
    <div id="div1">div 1</div>
    <div id="div2">div 2</div>
  </body>
</html>

JsFiddle

结果如下:

Scrollable area


¹ 在线文章可能以及问题中的图片肯定来自 http://phrogz.net/css/htmlvsbody.html 。需要注意的是,那篇文章是 2004 年写的。2004 年,当时的 CSS 2.1 草案所说的内容并不重要。重要的是 IE6 做了什么,这篇文章确实描述了 IE6 做了什么。

关于javascript - HTML:谁负责显示/隐藏滚动条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19757841/

相关文章:

javascript - 如何在 JavaScript 中使用回调函数结果填充数组?

javascript - Vue2 : data updated but html not?

jquery - 将值放入元素中

javascript - 使用 jQuery 查找重复的 LI 类名并在 UL 中对它们进行分组

javascript - 从 nodejs 的 https 请求访问 json 响应数据的问题

javascript - 如何将对象添加到单击事件处理程序内的 three.js 场景?

jQuery 仅在页面上显示/隐藏一项

html - CSS 媒体打印表不对齐边距自动

javascript - OnClick 功能在我的网站上不起作用

html - 侧边栏的 ARIA 地标角色,其中包含主导航