使用 Element.scrollIntoView() 的行为
wield behavior of Element.scrollIntoView()
我正在使用 Element.scrollIntoView()
。滚动正在工作,但它同时破坏了我整个页面的布局。以下是演示:
* {
margin: 0;
padding: 0;
}
html, body {
width: 100%;
height: 100%;
}
.content {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: hidden;
background-color: lightgray;
}
ul {
position: absolute;
width: 100%;
height: 300px;
left: 0;
bottom: 0;
background-color: gray;
overflow-y: scroll;
}
li {
list-style: none;
}
#div {
position: absolute;
width: 100%;
height: 300px;
left: 0;
bottom: -300px;
background-color: darkgray;
}
button {
position: absolute;
right: 0;
bottom: 0;
}
<div class=content>
<!-- it's the ul to scroll, staying at the bottom of the page -->
<ul>
<li id=li>abc</li>
<li>def</li>
</ul>
<!-- it's the div hidden under the bottom edge of the page -->
<div id=div>i should stay hidden.</div>
<button onclick=li.scrollIntoView();>scrollIntoView</button>
</div>
我在页面底边隐藏了一个<div>
。当我scrollIntoView
第一个<li>
in <ul>
时,隐藏的<div>
被拉了出来。不仅<div>
,整个页面的内容都被拉高了300px。
我希望它只是将 <li>
滚动到 <ul>
的视图中。为什么会影响整个页面的布局?
我想我自己找到了答案。参见 this answer。它是关于锚点的,但我认为 scrollIntoView
在内部共享相同的机制。
浏览器会尽力确保元素可见。当它在容器中时,它会首先将容器滚动到可见性最好的位置,因此内容会被拉起。
我正在使用 Element.scrollIntoView()
。滚动正在工作,但它同时破坏了我整个页面的布局。以下是演示:
* {
margin: 0;
padding: 0;
}
html, body {
width: 100%;
height: 100%;
}
.content {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: hidden;
background-color: lightgray;
}
ul {
position: absolute;
width: 100%;
height: 300px;
left: 0;
bottom: 0;
background-color: gray;
overflow-y: scroll;
}
li {
list-style: none;
}
#div {
position: absolute;
width: 100%;
height: 300px;
left: 0;
bottom: -300px;
background-color: darkgray;
}
button {
position: absolute;
right: 0;
bottom: 0;
}
<div class=content>
<!-- it's the ul to scroll, staying at the bottom of the page -->
<ul>
<li id=li>abc</li>
<li>def</li>
</ul>
<!-- it's the div hidden under the bottom edge of the page -->
<div id=div>i should stay hidden.</div>
<button onclick=li.scrollIntoView();>scrollIntoView</button>
</div>
我在页面底边隐藏了一个<div>
。当我scrollIntoView
第一个<li>
in <ul>
时,隐藏的<div>
被拉了出来。不仅<div>
,整个页面的内容都被拉高了300px。
我希望它只是将 <li>
滚动到 <ul>
的视图中。为什么会影响整个页面的布局?
我想我自己找到了答案。参见 this answer。它是关于锚点的,但我认为 scrollIntoView
在内部共享相同的机制。
浏览器会尽力确保元素可见。当它在容器中时,它会首先将容器滚动到可见性最好的位置,因此内容会被拉起。