scrollIntoView()方法的使用

192 阅读1分钟

需求 从帖子列表进入帖子详情页面自动定位到帖子详情页面的评论区域

<div class="">
   //文章内容
</div>
<div class="" id="comment">
  //评论区域
</div>
``

```js
```
mounted(){
     this.toLocal()
},
methods:{
    toLocal(){
        // 查找存储的锚点id
        let Id="comment";
        let toElement = document.getElementById(Id);
        //锚点存在跳转
        if(Id){
            this.$nextTick(() =>{
                toElement.scrollIntoView();
                
            })
        }
    }
}
``
可能不生效的原因:
       1.该方法需要页面完全加载后才能生效,运用vue中的this.$nextTick方法;
       2.this.toLocal() 方法放在返回详情的接口里面调用