/**html*/
<ul ref="scrollBarContent">
<li>最新</li>
<li>最新1</li>
<li>最新2</li>
<li>最新3</li>
<li>最新4</li>
<li>最新5</li>
</ul>
/**滑到指定区域*/
scrollOffset(index) { // index指定元素的下标
this.$nextTick(() => {
const content = this.$refs.scrollBarContent; //发生滑动的元素
const avtiveItem = content.children[index];
if (!avtiveItem) return false;
const scrollOption = {
top: 0,
left: 0,
behavior: "smooth",
};
const contentWidth = content.offsetWidth;
const avtiveItemWidth = avtiveItem.offsetWidth;
const avtiveItemLeft = avtiveItem.offsetLeft;
const offset = avtiveItemLeft - (contentWidth - avtiveItemWidth) / 2; // 需要移动的位置
scrollOption.left = offset;
content.scrollTo(scrollOption);
});
},
注:element.scrollTo(x-coord,y-coord)
x-coord:期望滚动到位置水平轴上距元素左上角的像素
y-coord:期望滚动到位置竖直轴上距元素左上角的像素
element.scrollTp(option):option有三个参数,left、top、behavior
behavior:滚动行为,支持参数smooth(平滑滚动),instant(瞬间滚动),默认值auto效果等同于instant。
另外scrollTo()和scrollBy()方法的区别:
scrollTo()方法是让view相对于初始的位置移动一段距离,scrollBy()方法则是让view相对于当前位置移动一段距离。