前言
当用户点击外部时,根据表示将滚动条滚动到指定数据位置,从而方便用户查看相关信息。下面以列表为例。
逻辑
- 使用
nextTick()
确保 DOM 已经更新 - 直接通过
document.querySelector
查找目标元素 - 使用
scrollIntoView
方法实现平滑滚动到视图中央
实现
html
<n-button @clcik="scrollToItem(5)">跳转到第五条数据</n-button>
<n-scrollbar style="max-height: 43vh;">
<div class="work-item" v-for="(item, index) in workList" :key="index">
<div class="row">
<div class="row-item">
<div class="title">{{ item.plateNo || '--' }}</div>
<div class="workLinkName">({{ item.jobTypeName || '--' }})</div>
</div>
</div>
</div>
</n-scrollbar>
js
/**
*滚动到指定索引的元素
*@params index 数据所在列表下标
*/
function scrollToItem(index) {
nextTick(() => {
if (workList.value.length > index) {
const targetElement = document.querySelector('.work-item:nth-child(' + (index + 1) + ')');
if (targetElement) {
targetElement.scrollIntoView({
behavior: 'smooth',
block: 'center'
});
}
}
});
}
效果
滚动条默认位置为开头,点击"跳转到第五条数据"按钮后,效果如下: