在标签上添加ref
属性来引用DOM元素,
$refs
来获取该DOM元素并调用scrollIntoView()
方法。使用ref="yearDiv"
在每个年份的div
元素上添加了一个引用。然后,在yearClick
方法中,我们通过this.$refs.yearDiv[year]
来获取对应年份的div
元素,并调用scrollIntoView()
方法来将该元素滚动到可见区域。方法如下:
yearClick(year) {
this.typeStyle = year;
const yearDiv = this.$refs.yearDiv[year];
yearDiv.scrollIntoView({ behavior: 'smooth' });
},
需要在Vue组件中更新HTML模板中添加data-year
属性,该属性的值是对应的年份,使用document.querySelector
函数来获取带有相应data-year
属性值的div
元素,并将其滚动到可见区域。
:data-year="year"
ref="yearDivs?
:class="{ rightActive: typeStyle === year }" //悬浮高亮
<div class="year-time">
<ul class="yearList" ref="yearList">
<li v-for="year in years" :key="year" :class="{ active: typeStyle === year }" @mouseover="yearClick(year)"
>
{{ year }}
</li>
</ul>
<ul class="right-content">
<div v-for="year in years" :key="year" :class="{ rightActive: typeStyle === year }" :data-year="year" ref="yearDiv">
<li v-for="item in contents[year]">{{ item }}</li>
</div>
</ul>
</div>
// 年份列表
const years = ['2019', '2020', '2021', '2022', '2023']
// 每个年份对应的内容
const contents: Record<string, string[]> = {
'2019': ['06月 一 ....'],
'2020': ['03月 一 AI......'],
'2021': ['03月 一 深入........'],
'2022': ['06月 一 建设布..........'],
'2023': ['05月 一 上线....','08月 一 启动安全....','09月 一 推出....']
}
const typeStyle = ref('2019')
const yearClick = (year: string) => {
typeStyle.value = year;
const yearDiv = document.querySelector(`[data-year="${year}"]`) as HTMLElement;
yearDiv?.scrollIntoView({ behavior: 'smooth' });
console.log(yearDiv, 'yearDiv');
};
css样式
.year-time {
display: flex;
padding-top: 30px;
padding-left: 80px;
justify-content: space-between;
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
.yearList {
width: 100px;
li {
width: 60px;
height: 60px;
line-height: 60px;
text-align: center;
font-size: 16px;
font-weight: bold;
border-radius: 50%;
cursor: pointer;
transition: all 0.3s;
}
}
.right-content {
width: calc(100% - 100px);
height: 400px;
overflow: auto;
padding-left: 80px;
padding-right: 20px;
scrollbar-width: thin;
scrollbar-color: #bbb transparent;
font-size: 14px;
}
.right-content::-webkit-scrollbar {
width: 6px;
}
.right-content::-webkit-scrollbar-track {
background-color: transparent;
}
.right-content::-webkit-scrollbar-thumb {
background-color: #bbb;
border-radius: 3px;
}
.right-content li {
margin-bottom: 20px;
}
.active {
background-color: #007aff;
color: #fff;
}
.rightActive {
font-weight: 700;
font-size: 16px;
color: #4391f1;
}
}