<template>
<div>
<div class="div">
<ul class="navgator">
<li class="navgatorLi" :class="{'isActive': index===navgatorIndex}" @click="handleLeft(index)" v-for="(item,index) in navgator" :key="item">{{item}}</li>
</ul>
<ul class="rightList">
<li :id="'id'+index" v-for="(item,index) in listBox" :key="item">{{item}}</li>
</ul>
</div>
</div>
</template>
<script>
export default {
data() {
return {
navgator: [
'List A',
'List B',
'List C',
'List D',
],
navgatorIndex: 0,
listBox: [
'A','B','C','D'
],
listBoxState: true,// Temporarily stop listening for page scrolling when clicking on the navigation bar.
};
},
created() {
},
mounted() {
let timeId;
window.addEventListener('scroll', () => {
// The following function is executed 100 milliseconds after the page scrolling stops.
clearTimeout(timeId);
timeId = setTimeout(() => {
this.scrollToTop();
console.log('Execution complete');
}, 100);
} , true);
},
methods: {
// Clicking on the navigation menu scrolls the page to the specified location.
handleLeft(index) {
this.navgatorIndex = index;
this.$el.querySelector(`#id${index}`).scrollIntoView({
behavior: "smooth", // Smooth transition
block: "start" // The top border is flush with the top of the viewport. Default value
});
this.listBoxState=false;
let timeId;
clearTimeout(timeId);
timeId = setTimeout(() => {
this.listBoxState=true;
},200);
},
// Listen for page elements to scroll and change the navigation bar selection.
scrollToTop() {
// Get the height of the window
var domHight = document.body.offsetHeight;
console.log(domHight)
// dom scroll position
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
if (this.listBoxState) {//The effect is to delay execution here when the navigation bar is clicked.
this.listBox.map((v,i) => {
// Get the distance of the listening element from the top of the window.
// var offsetTop = (`id${i}`).offsetTop;
// Get the height of the listening element itself
var scrollHeight = document.getElementById(`id${i}`).scrollHeight;
// if dom scroll position >= element distance from window && dom scroll position <= element distance from window + height of element itself
// means that the page has been scrolled to the visual area.
if (scrollTop >= offsetTop && scrollTop<=(offsetTop+scrollHeight)) {
// Navigation bar background color checked
this.navgatorIndex = i;
}
})
}
},
},
}
</script>
<style scoped>
.div {
width: 100%;
background: #ededed;
}
.navgator {
width: 200px;
position: fixed;
top: 0;
}
.navgator .navgatorLi {
width: 100%;
height: 1rem;
display: flex;
justify-content: center;
align-items: center;
border: 1px solid #ccc;
border-top: none;
}
.navgator .isActive {
color: #fff;
background: darkseagreen;
}
.rightList {
width: 560px;
margin-left : 200px;
}
.rightList li {
width: 100%;
height: 10rem;
display: flex;
justify-content: center;
align-items: center;
border: 1px solid #ccc;
}
</style>