踩坑scrollIntoView
Element.scrollIntoView() 方法让当前的元素滚动到浏览器窗口的可视区域内。
页面(容器)可滚动时才有用!
element.scrollIntoView(); // 等同于element.scrollIntoView(true)
element.scrollIntoView(alignToTop); //布尔参数
element.scrollIntoView(scrollIntoViewOptions); //对象参数
alignToTop | [可选],目前之前这个参数得到了良好的支持 |
---|---|
true | 元素的顶部将对齐到可滚动祖先的可见区域的顶部。对应于scrollIntoViewOptions: {block: "start", inline: "nearest"} 。这是默认值 |
false | 元素的底部将与可滚动祖先的可见区域的底部对齐。对应于scrollIntoViewOptions: {block: "end", inline: "nearest"} 。 |
scrollIntoViewOptions | [可选],目前这个参数浏览器对它的支持并不好,可以查看下文兼容性详情 |
---|---|
behavior | [可选]定义过渡动画。"auto" ,"instant" 或"smooth" 。默认为"auto" 。 |
block | [可选] "start" ,"center" ,"end" 或"nearest" 。默认为"center" 。 |
inline | [可选] "start" ,"center" ,"end" 或"nearest" 。默认为"nearest" 。 |
应用场景
- URL中hash标记的进化
- 聊天窗口滚动显示最新的消息
- 往一个列表添加item后滚动显示最新的添加的item
- 回到顶部(#)
- 滚动到指定位置(#xxx)
存在的问题
1】如果 父级有 滚动条 ,爷爷也有滚动条,那么会导致 都会动
2】react中使用的问题
想要实现的效果是:左边的列表切换时自动定位,而且右边的消息也需要自动定位
useEffect(() => {
document
?.getElementById('select_item_true')
?.scrollIntoView({ behavior: 'smooth', block: 'center' })
document
?.getElementById('badCase_true')
?.scrollIntoView({ behavior: 'smooth', block: 'center' })
}, [selectInfo])
通过setTimeout解决上面问题:
useEffect(() => {
document
?.getElementById('select_item_true')
?.scrollIntoView({ behavior: 'smooth', block: 'center' })
setTimeout(() => {
document
?.getElementById('badCase_true')
?.scrollIntoView({ behavior: 'smooth', block: 'center' })
}, 300)
}, [selectInfo])