[javascript]你还在用id进行锚点跳转?有点过时了嗷

428 阅读1分钟

背景

今天接到了一个需求,要求在输入框中,输入关键字。点击确定后,在长列表中完全匹配到对应的文字,还要高亮且定位到对应元素。

需求拆分

拿到这个需求,首先看到两个关键点

  1. 匹配
  2. 高亮
  3. 定位(跳转到对应位置)

假设列表数据如下:

const list = [
    {name:'item-A',id:'A'},
    {name:'item-B',id:'B'},
    {name:'item-C',id:'C'},
    {name:'item-D',id:'D'},
    {name:'item-E',id:'E'}
]

html结构如下:

<span v-for="item in list" :class="{'active':item.id === flagId}" :id="item.id">
    {{item.name}}
</span>

<style>
.active{
    color:red; // 高亮的样式
}
</style>

首先进行匹配:

const keyWords = "item-C" // 输入的值

for(let index = 0; index < list.length; index ++ ){
     if(list[index].name === 'keyWords'){
         // 此时表示匹配成功
         this.flagId = list[index].id // 高亮
     }
}

还差最后一步了,定位!

定位到某个元素的位置,可以有很多方法,如

  1. a标签跳转到id(锚点)
  2. 获取当前元素距离页面的位置(offsetTop),控制滚动条进行滚动(scrollTo)
  3. 推荐! 使用scrollIntoView()方法

那我们就采用第三种方法:

// 继续上面的代码块
// ...
     if(list[index].name === 'keyWords'){
         // 此时表示匹配成功
         this.flagId = list[index].id // 高亮
         document.getElementById(list[index].id).scrollIntoView({
             behavior:'smooth', // 是否丝滑滚动
             block:'center'  // 目标元素置于视区中间
         })
     }
// ...

结语

这样就可以实现丝滑而又高效的元素定位啦~