vue @scroll滚动条定位

html部分

<div class="left-body">
  <div
    :class="{ tab: true, 'active-tab': activeId == item.id }"
    v-for="item in tabList"
    :key="item"
    @click="jump(item.id)"
  >
    {{ item.title }}
  div>
div>
<el-divider direction="vertical" />
<div class="right-body" ref="rightRef" @scroll="rightScroll">
  <div class="title-style">titlediv>
  ....
div>

js部分

const jumpStep = ref(false);
const rightRef = ref();
function jump(val) {
  jumpStep.value = true;
  let titles = document.getElementsByClassName("title-style");
  rightRef.value.scrollTop = val == 1 ? 0 : titles[val - 1].offsetTop - titles[0].offsetTop;
  activeId.value = val;
}
function rightScroll() {
  if (jumpStep.value) {
    jumpStep.value = false;
    return;
  }
  let scrollTop = rightRef.value.scrollTop;
  let titles = document.getElementsByClassName("title-style");
  for (let i = 0; i < titles.length; i++) {
    if (
      (i < titles.length - 1 &&
        scrollTop >= titles[i].offsetTop - titles[0].offsetTop &&
        titles[i + 1].offsetTop - titles[0].offsetTop > scrollTop) ||
      (i == titles.length - 1 && scrollTop > titles[i].offsetTop - titles[0].offsetTop)
    ) {
      activeId.value = i + 1;
      break;
    }
  }
}

你可能感兴趣的:(前端小记,vue.js,javascript,前端)