1移动端小图标随手指移动而移动是手指触摸滑动

116 阅读1分钟

移动端手指滑动封装的代码

function moveanyway() { // 获取节点

  // 只需给滑动的盒子类名id,var block = document.getElementById('handle')
  // 就改这一个代码就行了
  var block = document.getElementById("handle")
  console.log(block)

  if (block) {
    var oW, oH

    // 绑定touchstart事件

    block.addEventListener(
      "touchstart",
      function (e) {
        var touches = e.touches[0]

        oW = touches.clientX - block.offsetLeft

        oH = touches.clientY - block.offsetTop

        // 阻止页面的滑动默认事件

        document.addEventListener("touchmove", defaultEvent, {
          passive: false,
        })
      },
      false
    )

    block.addEventListener(
      "touchmove",
      function (e) {
        var touches = e.touches[0]

        var oLeft = touches.clientX - oW

        var oTop = touches.clientY - oH

        if (oLeft < 10) {
          oLeft = 10

          if (oTop <= 10) {
            oTop = 10
          } else if (
            oTop >=
            document.documentElement.clientHeight - block.offsetHeight - 10
          ) {
            oTop =
              document.documentElement.clientHeight -
              block.offsetHeight -
              10
          }
        } else if (
          oLeft >
          document.documentElement.clientWidth - block.offsetWidth - 10
        ) {
          oLeft =
            document.documentElement.clientWidth - block.offsetWidth - 10

          if (oTop <= 10) {
            oTop = 10
          } else if (
            oTop >=
            document.documentElement.clientHeight - block.offsetHeight - 10
          ) {
            oTop =
              document.documentElement.clientHeight -
              block.offsetHeight -
              10
          }
        } else if (oTop < 10) {
          oTop = 10
        } else if (
          oTop >
          document.documentElement.clientHeight - block.offsetHeight - 10
        ) {
          oTop =
            document.documentElement.clientHeight - block.offsetHeight - 10
        }

        block.style.left = oLeft + "px"

        block.style.top = oTop + "px"
      },
      false
    )

    block.addEventListener(
      "touchend",
      function () {
        document.removeEventListener("touchmove", defaultEvent, {
          passive: false,
        })
      },
      false
    )
  }

  function defaultEvent(e) {
    e.preventDefault()
  }
}
//结束 1.移动端小图标随手指移动而移动是手指触摸滑动

// 2.点击按钮返回到页面顶部 。$('body').scrollTop({ y: 0 });这个的引入JQuery
function scrollTop() {
  $("body").scrollTop({ y: 0 })
  document.body.scrollTop = 0
  document.documentElement.scrollTop = 0
}
// 结束2.点击按钮返回到页面顶部

window.scroll(0, 0)
// 页面滚动了多少,可以通过 window.pageYOffset 得到
// 最后是页面滚动,使用 window.scroll(x,y)