vue+vux scrollTop无法实现定位到具体dom

先看一下最终的运行效果。

项目背景介绍:
技术栈: vue+vux+nodejs
需求:对汽车品牌列表可以按照字母进行索引定位

在开发中实现这种需求,心想还不是小菜一碟,作为一个饱经bug的程序员,别的我就不吹了,最起码Ctrl+C用的还是蛮不错的。
虽然我的复制能力MAX,但最起码的功能点还是要先梳理一下。
要实现这个功能统共分两步,
第一根据点击找到需要定位的位置,
第二触发页面滚动直接到这个位置。
so easy 嘛~
我以迅雷不接掩耳盗小铃铛之势就从我的程序小仓库里Ctrl+C了一段代码:
如下:
document.querySelector('#id'); // 获取点击节点找到节点对应的内容然后控制滚动
$(window).scrollTop($('#' + s + '1').offset().top); // 跳转到的位置

因为项目中没有用到jQuery,在用的时候要把$去掉。做了点小改动
document.documentElement.scrollTop = document.querySelector('#id').offset().top);

大吉大利,万无一失,程序跑起来。



貌似不行,翻遍全网只要是用scrollTop 都不行。
因为在vue中使用scrollTo不能赋值,总是0。
在解决程序疑难扎症这一点上,还真没遇到过对手。说了这么多到底怎么做呢?
请自行看下面的总结。

在试错过程中发现scrollIntoView()方法可以实现定位显示。

具体怎么实现的看下面的程序吧,总结一下有三点。
1.在需要定位到的dom中创建一个隐藏的dom
2.设置要定位的dom元素 position:relative 隐藏的dom position:absolute;
3.把点击点定位到隐藏的dom即可
嗯,暂时先总结到这里吧,下面有源码可供参考。
完美~

methods: {
jump(index){
document.getElementById("tchar_nav_"+index).scrollIntoView(); 
}, 
},

<!-- 字母导航 start -->
<div class="fixed-nav" style="opacity: 1; display: block;">
<ul class="rows-box">
<li v-for="(item, index) in listAll" :key="index" :id="'char_'+index">
<a @click="jump(index)">{{index}}</a>
</li> 
</ul>
</div>
<div class="alert" style="display: none;"><span>Y</span></div>
<!-- 字母导航 end -->

<div class="brand-list bybrand_list" v-for="(item, index) in listAll" :key="index">
<div :id="'tchar_nav_'+index" class="positionTo"></div>
<div :id="'char_nav_'+index" class="tt-small phone-title" :data-key="index">
<span>{{index}}</span></div>
<div class="box">
<ul>
<li id="char_nav_audi" v-for="(item2, index2) in item" :key="index2">
</li>
</ul>
</div>
</div>

<style lang="less" scoped>
.brand-list{
position: relative;
}
.positionTo{
position: absolute;
height: 30px;
background: transparent;
 30px;
background: red;
z-index: 99;
top:-46px;
}
</style>

  

原文地址:https://www.cnblogs.com/ligulalei/p/10622778.html