菜单导航栏点击导航滑动到指定位置&滑动到指定位置选中对应导航
效果
实现
话不多说直接上代码,有用素质三连(点赞、评论、加关注)
import { defineComponent, onBeforeUnmount, onMounted, reactive, ref } from "vue";
import { map } from "lodash";
import { css } from "@emotion/css";
export default defineComponent({
setup: () => {
const scrollRef = ref();
const state = reactive({
current: 1,
list: [
{ num: 1, title: "将军令" },
{ num: 2, title: "将军令" },
{ num: 3, title: "将军令" },
{ num: 4, title: "将军令" },
{ num: 5, title: "将军令" },
],
});
const handleScroll = (e) => {
state.list.forEach((item) => {
let scrollTopNum = document.getElementById(`anchor_${item.num}`).offsetTop - 200;
if (e.target.scrollTop >= scrollTopNum) {
state.current = item.num;
}
});
};
const toAnchor = (item) => {
let scrollTopNum = document.getElementById(`anchor_${item.num}`).offsetTop - 200;
scrollRef.value.scrollTop = scrollTopNum;
state.current = item.num;
};
onMounted(() => {
state.current = 1;
scrollRef.value.addEventListener("scroll", handleScroll, true);
});
onBeforeUnmount(() => {
scrollRef.value && scrollRef.value.removeEventListener && scrollRef.value?.removeEventListener("scroll");
});
return () => {
return (
<div
class={css({
display: "flex",
alignItems: "center",
p: {
color: "#666",
},
".content": {
width: 500,
height: 300,
overflowY: "scroll",
marginLeft: 300,
marginRight: 20,
},
})}>
<div className="content" ref={scrollRef}>
{map(state.list, (item) => {
return (
<div id={`anchor_${item.num}`}>
<div className="title">{item.title + item.num}</div>
<div>
<p>歌曲名 将军令 歌手名 吴克群</p>
<p>作词:吴克群</p>
<p>作曲:吴克群</p>
<p>我知道对有什么不对</p>
<p>我知道将军说的话不一定对</p>
<p>我知道对或错我自己能分辨</p>
<p>请你安静点请你安静点</p>
<p>Yeah</p>
<p>我知道对有什么不对</p>
<p>我知道外国的月亮没比较圆</p>
<p>我知道yo yo yo</p>
<p>不是我的语言</p>
<p>请你安静点请你安静点</p>
<p>Yeah</p>
<p>我是个小兵我绷紧了神经</p>
<p>在战场上</p>
<p>拼命听谁在发号施令</p>
<p>将军在微醺他方向分不清</p>
<p>西方人念经他全都听</p>
<p>不同的肤色说不同的话语</p>
<p>相同的节奏有不同的旋律</p>
<p>自己的文化要自己来说明</p>
<p>自己的舞台有我们自己顶</p>
<p>我知道对有什么不对</p>
<p>我知道将军说的话不一定对</p>
<p>我知道对或错我自己能分辨</p>
<p>请你安静点请你安静点</p>
</div>
</div>
);
})}
</div>
<el-steps direction="vertical" class={css({ height: "500px !important" })}>
{map(state.list, (item) => {
return (
<el-step
status={state.current == item.num ? "finish" : ""}
onClick={() => toAnchor(item)}
class={css({
cursor: "pointer",
})}
/>
);
})}
</el-steps>
</div>
);
};
},
});