Quick tip: using scrollIntoView(
2019-08-15 本文已影响4人
范小饭_
原文《Quick tip: using scrollIntoView() to show added elements to a container with overflow》
翻译:范小饭
快速提示:使用ScrollIntoView()向溢出的容器显示添加的元素
通常我们想要一个有溢出容器的接口:用页眉和页脚滚动。有一个问题是,当我们向容器中添加新的元素时,他们会添加早容器之后,但在用户向下滚动之前,他们不会显示出来。
在过去,我们通过比较scrollHeight和clientHeight以及设置元素的scrollTop属性来解决这个问题,这很容易出错,看起来过于复杂。
输入scrollIntoView,使用此API确保向用户显示新元素就像在元素本身上调用它一样简单
假设我们有以下字符列表和一个按钮来添加更多字符。
HTML:
<div class="scrollbody">
<ul>
<li>Billy Butcher</li>
<li>Hughie Campbell</li>
<li>Mother's Milk</li>
<li>The Frenchman</li>
</ul>
</div>
<button>Add new character</button>
在css中,我们限制这个容器溢出滚动
.scrollbody {
height: 6em;
overflow: scroll;
}
通过一小段js,现在,当我们点击按钮的时候可以随时添加字符。
let characters = ['The Female (of the Species)',
'Lieutenant Colonel Greg D. Mallory','The Legend','The Homelander',
'Black Noir','Queen Maeve','A-Train','The Deep','Jack from Jupiter',
'The Lamplighter','Starlight','Mister Marathon','Big Game',
'DogKnott','PopClaw','Blarney Cock','Whack Job',
'Gunpowder','Shout Out'];
let count = 0;
document.querySelector('button').addEventListener('click', (ev) => {
if (count < characters.length) {
let item = document.createElement('li');
item.innerText = characters[count];
document.querySelector('ul').appendChild(item);
count = count + 1;
}
ev.preventDefault;
});
现在, 如果你正在尝试,你会看见新的字符串实际上已经添加了,但是直到你滑动的时候才看见它。
image这个体验很不好,为了补救这个,你需要的是在添加新列表项后添加scrollIntoView调用。
/* list of characters */
let count = 0;
document.querySelector('button').addEventListener('click', (ev) => {
if (count < characters.length) {
let item = document.createElement('li');
item.innerText = characters[count];
document.querySelector('ul').appendChild(item);
item.scrollIntoView();
count = count + 1;
}
ev.preventDefault;
});
image
作为额外的奖金,你可以定义平滑滚动,让滚动更加慢不卡顿
/* list of characters */
let count = 0;
document.querySelector('button').addEventListener('click', (ev) => {
if (count < characters.length) {
let item = document.createElement('li');
item.innerText = characters[count];
document.querySelector('ul').appendChild(item);
item.scrollIntoView({behavior: 'smooth'});
count = count + 1;
}
ev.preventDefault;
});
image
另一个提示是继续查看标准中的内容,而不是在StackOverFlow上找到旧的解决方案并保持过于复杂而不是浏览器优化的代码。