vue锚点定位通过点击a标签实现(vue2实现结果 文字)

174 阅读1分钟

image.png

image.png

通过点击录播滚动到指定位置

默认a标签的话 点击是会给路径后面拼接参数字段 毕竟不优雅 如果要返回要返回两次

上代码实现
html
   <div class="nav_scroll">
    <a href="javascript:void(0)" class="_scroll" v-if="hdList && hdList.length>0" @click="scrollToElement('#pane-brand')">
      <img src="/img/special_topic/video_scroll.png" alt=""> 短视频</a>
    <a href="javascript:void(0)" class="_scroll" v-if="zlbList && zlbList.length>0" @click="scrollToElement('#pane-img')">
      <img src="/img/special_topic/voice_scroll.png" alt=""> 直录播</a>
    <a href="javascript:void(0)" class="_scroll" v-if="zlList && zlList.length>0" @click="scrollToElement('#pane-zl')">
      <img src="/img/special_topic/pic_scroll.png" alt=""> 展览</a>
    <a href="javascript:void(0)" class="_scroll" v-if="jsList && jsList.length>0" @click="scrollToElement('#pane-text')">
      <img src="/img/special_topic/pic_scroll.png" alt=""> 培训</a>
    <a href="javascript:void(0)" class="_scroll" v-if="ypList && ypList.length>0" @click="scrollToElement('#pane-yp')">
      <img src="/img/special_topic/audio_scroll.png" alt=""> 音频</a>
    <a href="javascript:void(0)" class="_scroll" v-if="zxList && zxList.length>0" @click="scrollToElement('#pane-news')">
      <img src="/img/special_topic/pic_scroll.png" alt=""> 动态资讯</a>
  </div>
  
  这边a标签设置javascript:void(0)防止带个参数字段
  
  <div class="pane-brand" id="pane-brand" v-if="hdList && hdList.length>0"></div>
  <div class="pane-brand" id="pane-brand" v-if="hdList && hdList.length>0"></div>
  <div class="pane-brand" id="pane-brand" v-if="hdList && hdList.length>0"></div>
  <div class="pane-brand" id="pane-brand" v-if="hdList && hdList.length>0"></div>
  <div class="pane-brand" id="pane-brand" v-if="hdList && hdList.length>0"></div>
      
这边id自己修改对应上方

css
.nav_scroll{
  scroll-behavior: smooth;
  background-color: #fff;
  height: 100px;
  text-align: center;
  line-height: 100px;
  ._scroll{
    padding: 0 25px;
    font-size: 32px;
    display: inline-block;
    color: #666;
    img{
      width: 24px;
      height: 24px;
      z-index: 9;
      margin-right: 4px;
    }
  }
}

js
// 点击tab拦标题滑动
scrollToElement(selector) {
  this.$nextTick(() => {
    const element = document.querySelector(selector);
    console.log(selector, element);
    if (element) {
      element.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' });
    }
  });
},