您当前的位置: 首页 > 

Vue项目通过scrollIntoView实现锚点点击页面平滑滚动

彭世瑜 发布时间:2019-10-14 16:06:40 ,浏览量:2

实现方式

element.scrollIntoView();

参考: https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView

实现代码

goAnchor(selector) {
  this.$el.querySelector(selector).scrollIntoView({
      behavior: "smooth",  // 平滑过渡
      block:    "start"  // 上边框与视窗顶部平齐。默认值
  });
}

完整示例代码


  
    
    
      Java
      Python
      Javascript
    

    
    
      Java
      
    

    
      Python
      
    

    
      Javascript
      
    
  




export default {
  methods: {
    // 标签滚动
    goAnchor(selector) {
      this.$el.querySelector(selector).scrollIntoView({
          behavior: "smooth",  // 平滑过渡
          block:    "start"  // 上边框与视窗顶部平齐。默认值
      });
    }
  }
};



.main {
  width: 600px;
  margin: 0 auto;
  margin-top: 20px;
}

.nav a {
  text-decoration: none;
  color: #333;
  padding: 0 10px;
  margin: 0 5px;
  background: #9e9e9e;
  line-height: 2;
}

.nav {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.item{
    margin-top: 20px;
}

.title{
    background: #9e9e9e;
    line-height: 2;
}
.content {
  height: 300px;
  background: #eeeeee;
}

在这里插入图片描述

问题

1、要获取的节点不在当前组件内,没有ref 引用,可以直接获取全局的节点,使用document

document.querySelector(selector).scrollIntoView({
      behavior: "smooth",  // 平滑过渡
      block:    "start"  // 上边框与视窗顶部平齐。默认值
  });

2、如果在循环列表,或多个子节点中使用id选择器要注意,id不能重复,可以使用uuid给每个元素分配一个唯一id。

import { v4 as uuidv4 } from 'uuid';

console.log(uuidv4());
// 92b8a6bd-f1fd-4b52-b8a0-6178a0e76828

具体使用方式见: Node.js:创建一个随机的UUID

关注
打赏
1688896170
查看更多评论

彭世瑜

暂无认证

  • 2浏览

    0关注

    2727博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0511s