先看效果:
实现侧导航第一步肯定是控制侧导航的显示隐藏,然后通过点击事件回到需要的位置,而这个位置我不希望它写死距离,就可以用到描点的方式来实现了。控制描点元素位置来实现内容变化还是滑动在想要的位置。但是直接使用描点不会具有平滑效果,其实浏览器原生提供了一种方法scrollIntoView
,它可以操作元素滚动到可视区域内,而且可以在后面添加滚动的效果。
如果需要实现回到顶部那可以将描点元素写在页面顶部然后通过 transform: translateY();实现平移到页面最顶部且看不到的区域,这样使用scrollIntoView
来将顶部元素滚动到可视区域就等同于页面滚动到最顶部来实现回到顶部功能。
需要滚动到可视区域的元素.scrollIntoView({ behavior: "smooth" });
后面可以通过 behavior: "smooth"来指定滚动方式为平滑效果。
以下是示例的完整代码:
<template>
<div class="hello">
<!-- 回到顶部描点 -->
<div class="goback-top" ref="goBackTop"></div>
<!-- 回到顶部按钮 -->
<div class="goback" v-show="isShowGoTop" @click="scrollTop">回到顶部</div>
<h1>{{ name }}</h1>
<div class="container">
<ul>
<li
v-for="(item, index) in bgcList"
:key="index"
:style="{ backgroundColor: item }"
></li>
</ul>
</div>
</div>
</template>
<script>
export default {
data() {
return {
name: "我是标题",
isShowGoTop: false,
bgcList: [
"pink",
"skyblue",
"orange",
"pink",
"skyblue",
"orange",
"pink",
"skyblue",
"orange",
],
};
},
methods: {
// 监听滚动事件使回到顶部显示隐藏
handleScroll() {
const scrollHeight = window.scrollY; //获取页面滚动卷去的高度
// 处理滚动高度
this.isShowGoTop = scrollHeight >= 350 ? true : false;
},
// 点击回到顶部
scrollTop() {
const goBackTop = this.$refs.goBackTop;
goBackTop.scrollIntoView({ behavior: "smooth" });
},
},
mounted() {
window.addEventListener("scroll", this.handleScroll);
},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.goback-top {
transform: translateY(-200px);
}
.container {
height: 200vh;
}
.goback {
z-index: inherit;
padding: 10px;
position: fixed;
width: 30px;
height: 40px;
right: 50px;
bottom: 200px;
font-size: 14px;
background-color: black;
color: white;
cursor: pointer;
}
li {
list-style: none;
height: 100px;
}
</style>