实现网页APP-悬浮可移动按钮(源码)

/**

  • @Date 31/10/2018
  • @description 实现按钮固定,不随屏幕滑动 + 按钮可自由移动
  •         使用touch事件实现按钮自由移动和点击触发事件
    
  •          touchstart - 手指触摸屏幕时触发
    
  •          touchmove -  手指在屏幕上滑动时连续的触发
    
  •          touchend - 手指离开屏幕时触发
    
  • 踩坑:–安卓机点击和拖动事件触发不灵敏
    */
    移动前移动后

代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>悬浮可移动按钮</title>
<style type="text/css">
   button{
      position:fixed;
      top:70px;
      width:150px;
      height:150px;
      font-size:30px;
      color:#fff;
      border-radius:50%;
      background-color:#e53935;
   }
</style>
</head>
<body>
     
     <button id = "MotionButton" >可拖拽</button>
     
</body>
<script>
    window.function(){
     var flag=0;
     var motion = document.getElementById('MotionButton');
     
     var disX,disY;    //元素左/上 ‘半径’
     var moveX,moveY;  
     var L,T;    //可移动范围
     var starX,starY;
     var starXEnd,starYEnd;
     
     motion.addEventListener('touchstart',function(e){
      flag = 0;
      e.preventDefault(); //阻止触摸按钮时页面滚动和缩放
      //获取元素左/上边到中心(clientX,clientY)的距离
            disX = e.touches[0].clientX - this.offsetLeft;
            disY = e.touches[0].clientY - this.offsetTop;
      //手指按下屏幕时的坐标
            starX = e.touches[0].clientX;
            starY = e.touches[0].clientY;
     });
     motion.addEventListener('touchmove',function(e){
            flag = 1;
            L = e.touches[0].clientX - disX ;
            T = e.touches[0].clientY - disY ;
      //移动时当前位置和起始位置的差值
           starXEnd = e.touches[0].clientX - starX;
            starYEnd = e.touches[0].clientY - starY;
      
      if(L<0){
       L = 0; //限制拖拽的X范围,不能拖出屏幕
      }else if(L > document.documentElement.clientWidth - this.offsetWidth){
       L=document.documentElement.clientWidth - this.offsetWidth;
      }
      if(T<0){
                T=0;  //限制拖拽的Y范围,不能拖出屏幕
            }else if(T>document.documentElement.clientHeight - this.offsetHeight){
                T = document.documentElement.clientHeight - this.offsetHeight;
            }
      
      moveX = L +'px';
      moveY = T +'px';
      this.style.left = moveX;
      this.style.top = moveY;
     });
     motion.addEventListener('touchend',function(e){
      if(flag === 0){
       e.preventDefault();
       /*
       点击处理事件.....
       */
       window.location.href = 'https://blog.csdn.net/';
      }
      
     });
    }
</script>
</html>

**涉及知识点:(1)offset和client **
在这里插入图片描述

涉及知识点:(2)touch事件中的touches、targetTouches和changedTouches
touches: 当前屏幕上所有触摸点的列表;
targetTouches: 当前对象上所有触摸点的列表;
changedTouches: 涉及当前(引发)事件的触摸点的列表;

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值