uniapp实现锚点定位并增加动画及相关问题处理

一、通过 scroll-view 组件自带的 scroll-into-view 属性处理

        如下代码中,toview 是目标元素的id,即循环数据中的item.id,items的数据结构是:

[
  {
      name: "课程1",
      id: 1
  },
  .......
]


  
        {{ item.name }}
   

这样的话,可以发现浏览器会报错uniapp实现锚点定位并增加动画及相关问题处理_第1张图片

原因是 【scroll-into-view】的值需要是一个string,并且也不能是string类型的数字,'1'也不行,为了解决这个问题,可以给id加个前缀如下:


  "'id_'+item.id" class="scroll-item">
        {{ item.name }}
   

二、如何给锚点定位添加动画效果

function smoothScrollToAnchor(anchorId:string) {
  const anchor = document.getElementById(anchorId);
  if (anchor) {
    anchor.scrollIntoView({ behavior: 'smooth' }); // 使用平滑滚动效果
  }
}

定义一个是js方法,需要锚点定位的时候传入 锚点id,也就是上面 代码中的 id_'+item.id 就可以啦

三、实现过程中还可能遇到一个问题就是 初始化不生效,如下可以加一个setTimeout 进行处理

watch(props, (newValue) => {

  if(props.curClassId){

    setTimeout(()=>{

      smoothScrollToAnchor('id'+props.curClassId)

    }, 100)

  }

}, { deep: true, immediate: true })

Tips:今天的分享就这些啦,如果有更好的实现方案,欢迎大家留言讨论哟!

你可能感兴趣的:(uniapp,uni-app,scroll,锚点)