/**html*/
<ul ref="scrollBarContent">
<li>最新</li>
<li>最新1</li>
<li>最新2</li>
<li>最新3</li>
<li>最新4</li>
<li>最新5</li>
</ul>
/**滑到指定區(qū)域*/
scrollOffset(index) { // index指定元素的下標(biāo)
this.$nextTick(() => {
const content = this.$refs.scrollBarContent; //發(fā)生滑動(dòng)的元素
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; // 需要移動(dòng)的位置
scrollOption.left = offset;
content.scrollTo(scrollOption);
});
},
注:element.scrollTo(x-coord,y-coord)
x-coord:期望滾動(dòng)到位置水平軸上距元素左上角的像素
y-coord:期望滾動(dòng)到位置豎直軸上距元素左上角的像素
element.scrollTp(option):option有三個(gè)參數(shù)耸棒,left悯姊、top、behavior
behavior:滾動(dòng)行為,支持參數(shù)smooth(平滑滾動(dòng))轻黑,instant(瞬間滾動(dòng)),默認(rèn)值auto效果等同于instant哲戚。
另外scrollTo()和scrollBy()方法的區(qū)別:
scrollTo()方法是讓view相對(duì)于初始的位置移動(dòng)一段距離存淫,scrollBy()方法則是讓view相對(duì)于當(dāng)前位置移動(dòng)一段距離。