Home/Article/website/nuxt3 setup ts 实现锚点跳转及滚动监听最简例子
nuxt3
<!-- Html结构 -->
<template>
<div>
<div class="list">
<ul>
<li v-for="(item,index) in title_list" :key="index">
<span ref="spans" :style="{color: activeStep === index ? '#1987e1' : '#000000'}"
@click="jump(index)">
{{item.title}}
</span>
</li>
</ul>
</div>
<div class="result" @scroll="onScroll" >
<div class="scroll-item"><span>第一内容</span></div>
<div class="scroll-item"><span>第二内容</span></div>
<div class="scroll-item"><span>第三内容</span></div>
<div class="scroll-item"><span>第四内容</span></div>
</div>
</div>
</template>
<!-- 功能实现代码 -->
<script lang="ts" setup>
let title_list =[
{title:'第一'},
{title:'第二'},
{title:'第三'},
{title:'第四'},
]
const jump = (index:any) => {
var items = document.querySelectorAll(".scroll-item");
for (var i = 0; i < items.length; i++) {
if (index === i) {
items[i].scrollIntoView({
block: "start",//默认跳转到顶部
behavior: "smooth"//滚动的速度
});
}
}
}
let activeStep:any = ref(0) //当前页面动态数据使用ref()
const onScroll = (e: any) => {
let scrollItems: any = document.querySelectorAll(".scroll-item");
for (let i = scrollItems.length - 1; i >= 0; i--) {
// 判断滚动条滚动距离是否大于当前滚动项可滚动距离
let judge = e.target.scrollTop >= scrollItems[i].offsetTop - scrollItems[0].offsetTop;
if (judge) {
activeStep.value = i;
// console.log(activeStep)
break;
}
}
}
</script>
<!-- 样式 -->
<style>
.list {
width: 100%;
height: 40px;
margin-bottom: 20px;
background: pink;
}
ul {
width: 100%;
height: 40px;
line-height: 40px;
list-style: none;
}
li {
float: left;
width: 20%;
font-size: 30px;
}
li>span {
cursor:pointer;
}
.result {
width: 100%;
height: 500px;
overflow: scroll;
}
.scroll-item {
width: 100%;
height: 500px;
margin-top:20px;
background: yellow;
}
.scroll-item>span {
font-size: 40px;
}
.scroll-item:first-child {
margin-top: 0;
}
.scroll-item:last-child {
height: 500px;
}
/* 最后一个元素的最小高度要大于等于父元素的高度,如果scroll-item为高度自适应的话,那么最后一个scroll-item就得设置min-height:100% */
</style>
上一篇: nuxt3 setup ts 实现锚点跳转及滚动监听好用例子下一篇: 2024年饿了么外卖红包优惠券领取方式大全