html、body和window在以编程方式滚动时是如何交互的



我一直在尝试实现滚动到顶部按钮。在网上搜索我发现了这段代码:

$('html, body').animate({scrollTop:0}, 'slow');  

我很困惑,他们为什么要同时滚动htmlbody,然后在body标签上玩overflow: hidden,我注意到你不能同时有htmlbody的滚动条。然后在MDN上,我找到了另一种实现相同功能的方法:

window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
});

正如我们所知,window是全局对象,显然不能滚动。

  1. window.scroll是在内部滚动html元素还是body元素
  2. body元素是否可以滚动?我在html上尝试了overflow: hidden,然后在body上尝试了overflow: scroll,但没有看到滚动条

window.scroll()有效地滚动了document.scrollingElement*,它现在被定义为<html>元素,但在一些UA中曾经是<body>元素,并且仍然处于Quirks模式。

这个document.scrollingElement是一个相对较新的添加,这就是为什么您仍然可以找到同时处理<body><html>的旧代码来支持所有浏览器。

*根据规格视口";但这归结为相同的,因为CCD_;文档的根元素作为相关联的元素";到实际的";执行滚动";操作

const frameContent = `<html>
<body><h1 style='height:300vh'>%s Mode</h1>
<script>
scroll(0, 200);
parent.postMessage({
compatMode: document.compatMode,
html: document.documentElement.scrollTop,
body: document.body.scrollTop,
}, '*')
</script>`;
document.querySelectorAll("iframe").forEach((el, i) => {
el.src = `data:text/html,` + encodeURIComponent(
(i ? "<!DOCTYPE html>" : "") + // set the first frame to Quirk mode
frameContent.replace("%s", i ? "Default" : "Quirk")
);
});
onmessage = ({data}) => console.log(data)
<iframe></iframe>
<iframe></iframe>

  1. window.scroll在内部滚动html元素还是body元素

两者都没有。它滚动视口。滚动的精确描述在CSSOM视图规范中给出

  1. 是否可以滚动body元素?我尝试了溢出:隐藏在html上,然后溢出:在body上可见,但看不到滚动条

是。但是CCD_ 24不会显示滚动条。您需要overflow: scrolloverflow: auto。要使其滚动,内容必须溢出正文。例如

html {
overflow: scroll;
width: 630px;
}  
body { 
height: 80px;
overflow: auto;
}
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

在这里你可以看到两个垂直滚动条。视口上的一个是由html元素上的overflow: scroll强制显示的,另一个是由于内容溢出而在body上显示的,它有overflow: auto

如果两个滚动条的内容都溢出了,我们可以让它们都滚动。

html  {
overflow: auto;
border:2px solid red;
}  
body { 
height: 110vh; /* overflows the viewport - but note: 
as you can see from the red and 
blue borders, not the html emlement. */
overflow: auto;
border:2px solid blue;
}
p { 
height: 130vh; /* overflows the body element */
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<p>

最新更新