美文网首页
【JavaScript】浏览器中平滑位移到指定选择器元素的位置

【JavaScript】浏览器中平滑位移到指定选择器元素的位置

作者: burningalive | 来源:发表于2018-11-13 14:47 被阅读0次

    参数填选择器即可, 比如用于回到顶部时只需要ele.addEventListener(moveTo('body'));

    function moveTo (sel) {
      const tar = document.querySelector(sel)
      if (tar) {
        let doc = document
        // 不传入参数时返回当前浏览器scrollTop值, 传入参数时先设置当前页面scrollTop值再返回设置后的scrollTop值
        const docTop = function (...arg) {
          if (arg.length === 0) {
            return doc.body.scrollTop || doc.documentElement.scrollTop
          } else if (arg.length === 1) {
            doc.body.scrollTop = arg[0]
            doc.documentElement.scrollTop = arg[0]
            return docTop()
          }
        }
        return function () {
          const tarTop = tar.offsetTop
          const clickTop = docTop()
          let status
          if (clickTop < tarTop) status = 'down'
          else status = 'up'
          const SPEED = Math.abs(tarTop - clickTop) / 60
          let lastTop = undefined
          const scrollStep = function () {
            let scrollTop = docTop()
            lastTop = scrollTop
            if (status === 'down') {
              scrollTop += SPEED
              if (scrollTop > tarTop) {
                scrollTop = tarTop
                status = 'stop'
              }
            } else if (status === 'up') {
              scrollTop -= SPEED
              if (scrollTop < tarTop) {
                scrollTop = tarTop
                status = 'stop'
              }
            }
            const thisTop = docTop(scrollTop)
            if (thisTop === lastTop) {
              status = 'stop'
            }
            if (status === 'stop') {
              return
            }
            requestAnimationFrame(scrollStep)
          }
          scrollStep()
        }
      } else {
        return undefined
      }
    }
    

    相关文章

      网友评论

          本文标题:【JavaScript】浏览器中平滑位移到指定选择器元素的位置

          本文链接:https://www.haomeiwen.com/subject/dbqlfqtx.html