美文网首页
tab 导航-页面滚动吸顶 + 双向锚点

tab 导航-页面滚动吸顶 + 双向锚点

作者: 淡忘_b591 | 来源:发表于2021-06-29 23:01 被阅读0次
<template>
  <div class="page">
    <div class="banner"></div>
    <nav class="tabNav" :class="{ tabFixed: isFixed }">
      <a
        v-for="(item, index) in tabList"
        :key="item"
        :class="{ active: index == activeIndex }"
        @click="tabChange(index)"
        >{{ item }}</a
      >
    </nav>
    <div class="box1 scrollDiv">模块1</div>
    <div class="box2 scrollDiv">模块2</div>
    <div class="box3 scrollDiv">模块3</div>
    <div class="box4 scrollDiv">模块4</div>
  </div>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      activeIndex:0,
      isFixed: false,
      tabList: ["标签一", "标签二", "标签三", "标签四"],
    };
  },
  mounted() {
    window.addEventListener("scroll", this.scrollHander);
  },
  destroyed() {
    window.removeEventListener("scroll", this.scrollHander);
  },
  methods: {
    tabChange(index) {
      let top =
        document.getElementsByClassName("scrollDiv")[index].offsetTop - 60;
      window.scrollTo({
        top,
        behavior: "smooth",
      });
    },
    scrollHander() {
      let scrollHeight =
        document.documentElement.scrollTop ||
        window.pageYOffset ||
        document.body.scrollTop;
      if (scrollHeight > 300) {
        this.isFixed = true;
      } else {
        this.isFixed = false;
      }
    },
  },
};
</script>

<style>
.banner {
  width: 100%;
  height: 300px;
  color: antiquewhite;
}
.tabNav {
  width: 100%;
  height: 60px;
  line-height: 60px;
  background: #ccc;
  text-align: left;
}
.tabFixed {
  position: fixed;
  top: 0;
  left: 0;
}
a {
  margin-right: 20px;
  cursor: pointer;
}
.active{
  color: aqua;
}
.box1,
.box2,
.box3,
.box4 {
  width: 100%;
  height: 300px;
  line-height: 300px;
  background: forestgreen;
}
.box1 {
  background: forestgreen;
}
.box2 {
  background: fuchsia;
}
.box3 {
  background: goldenrod;
}
.box4 {
  background: hotpink;
}
</style>

相关文章

网友评论

      本文标题:tab 导航-页面滚动吸顶 + 双向锚点

      本文链接:https://www.haomeiwen.com/subject/rahlultx.html