基于nuxt+ts封装的锚点功能
效果
代码
子组件
<script lang='tsx'>
import { Component, Vue, Prop, Emit, Watch, Mutation } from 'nuxt-property-decorator'
interface anchorItem {
icon: string,
text: string,
class: string,
href: string
}
interface anchorContentItem {
title: string,
secondTitle: string
}
@Component
export default class SolutionItemComponent extends Vue {
@Prop({
type: Array,
default () {
return []
}
}) public anchorArr!: Array<anchorItem>;
@Prop({
type: Array,
default () {
return []
}
}) public anchorContent !: Array<anchorContentItem>
// 是否在顶部
public isPosTop: boolean = false
// 锚点点击事件
public clickAnchor (item) {
this.anchorArr.forEach(item => {
item.class = ''
})
item.class = 'active'
let anchorTop: any = this.$refs.anchorTop
let anchorTopHeight = anchorTop.clientHeight
let menu: any = document.getElementsByClassName('head-box')[0]
let menuHeight = menu.clientHeight
let element: any = document.getElementById(item.href)
let elementTop = element.offsetTop
let oldScrollTop = document.getElementsByClassName('container-box')[0].scrollTop
if (oldScrollTop < elementTop - anchorTopHeight - menuHeight) {
let timer = setInterval(function () {
let scrollTop = document.getElementsByClassName('container-box')[0].scrollTop
if (scrollTop >= elementTop - anchorTopHeight - menuHeight) {