Vue路由hash模式下锚点滚动实现

1.Vue路由在hash模式下# 已被占用: 无法使用浏览器的锚点功能: 使用js实现锚点滚动功能

Vue路由hash模式下锚点滚动实现_第1张图片

/**

 * 使用js实现锚点滚动功能;字符串需要是'#id'锚点格式;数字的话标识要滚动的位置

 * @param {String,Number} selector

 */

export function goAnchor(selector) {

    let top = 0

    const scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop

    if (typeof selector === 'number') {

        top = selector - scrollTop

    } else {

        const anchor = document.querySelector(selector) || { offsetTop: 0 }

        top = anchor.offsetTop - scrollTop

    }

    window.scrollBy({ top, behavior: 'smooth' })

}

2.项目要求实现的效果

Vue路由hash模式下锚点滚动实现_第2张图片

点击轮播图和右侧的图片,跳转到别的页面中对应的文本内容去:

Vue路由hash模式下锚点滚动实现_第3张图片

3.在项目中使用:
Vue路由hash模式下锚点滚动实现_第4张图片

 Vue路由hash模式下锚点滚动实现_第5张图片

Vue路由hash模式下锚点滚动实现_第6张图片

 Vue路由hash模式下锚点滚动实现_第7张图片Vue路由hash模式下锚点滚动实现_第8张图片

 Vue路由hash模式下锚点滚动实现_第9张图片

你可能感兴趣的:(vue.js,javascript,前端)