Vue中如何正常使用锚点定位?

问题:

项目中会有一些功能需要用到锚点定位,比如文章目录、点击标题跳转到正文内容等等。但vue的路由设置默认为hash模式,正常使用a标签的锚点定位,在浏览器刷新/后退/前进时,路由会匹配不上,导致页面无法正常渲染

解决方案:

方法一

在router配置里添加(亲测有效):

mode: 'history',
srcollBehavior(to,from,savedPosition){
    if(to.hash){
     return {
        selector:to.hash
      }
    }
 }

方法二:

定义点击事件

<template>
 <div>
  <div><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" @click="goAnchor('#anchor-'+index)" v-for="index in 20"> {{index}</a></div>
  <div :id="'anchor-'+index" class="item" v-for="index in 20">{{index}</div>
</div>
</template>
methods: {
  goAnchor(selector) {
     var anchor = this.$el.querySelector(selector)
     document.documentElement.scrollTop = anchor.offsetTop
  }
 }

方法三:

自定义指令

<template>
<div>
  <div><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" v-anchor="index" v-for="index in 20"> {{index}} </a></div>
  <div :id="'anchor-'+index" class="item" v-for="index in 20" >{{index}}</div>
</div>
</template>

main.js  定义全局指令  方便其他地方复用

Vue.directive('anchor',{
inserted : function(el,binding){
el.onclick = function(){
  document.documentElement.scrollTop = $('#anchor-'+binding.value).offset().top
}
}
})

方法四:

定义点击事件

document.querySelector(“要返回地方的id”).scrollIntoView(true);

<template>
    <div>
        <div id='header'></div>
        <div class='footer' @click='returnTop'></div>
    </div>
</template>
methods:{
  returnTop(){
   document.querySelector("#header").scrollIntoView(true);
  }
 }

拓展:

scrollIntoView是一个与页面(容器)滚动相关的API(官方解释),该API只有boolean类型的参数能得到良好的支持(firefox 36+都支持),所以在这里只讨论参数Boolean类型的情况。

调用方法为 element.scrollIntoView() 参数默认为true。

参数为true时调用该函数,页面(或容器)发生滚动,使element的顶部与视图(容器)顶部对齐;

参数为false时,使element的底部与视图(容器)底部对齐。

TIPS:页面(容器)可滚动时才有用!

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值