悬浮球

277 阅读1分钟

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
    <title>悬浮球</title>
</head>
<body>
    <div id="id" style="width: 35px;height: 35px;position: fixed;left: 0px;top: 100px"><img style="width: 35px;height: 35px;" src="qiu.png"></div>

    <script type="text/javascript">
                var _x_start,_y_start,_x_move,_y_move,_x_end,_y_end,left_start,top_start;
                var tarDiv = document.getElementById("id");
                //按下
                tarDiv.addEventListener("touchstart",function(e) {   
                    _x_start=e.touches[0].pageX;//起始点击位置
                    _y_start=e.touches[0].pageY;//起始点击位置
                   left_start = tarDiv.style.left;//元素左边距
                    console.log( left_start )
                   top_start = tarDiv.style.top;//元素上边距
                });
                //移动
                tarDiv.addEventListener("touchmove",function(e) {   
                    e.preventDefault();//取消事件的默认动作。
                    _x_move=e.touches[0].pageX;//当前屏幕上所有触摸点的集合列表
                    _y_move=e.touches[0].pageY;//当前屏幕上所有触摸点的集合列表
                    //左边距=当前触摸点-鼠标起始点击位置+起始左边距
                    tarDiv.style.left = parseFloat(_x_move)-parseFloat(_x_start)+parseFloat(left_start)+"px"
                    //上边距=当前触摸点-鼠标起始点击位置+起始上边距
                    tarDiv.style.top = parseFloat(_y_move)-parseFloat(_y_start)+parseFloat(top_start)+"px"
                });
                //松开
                tarDiv.addEventListener("touchend",function(e) {

                    var bodyW=window.screen.width/2;//屏幕宽的一半
                    var bodyH=window.screen.height;//屏幕高
                    var _x_end=e.changedTouches[0].pageX;//松开位置
                    var _y_end=e.changedTouches[0].pageY;//松开位置
                    var divH= tarDiv.style.height;//元素高
                    var divW= tarDiv.style.width;//元素宽
                    //当最终位置在屏幕左半部分
                    if(_x_end<bodyW){
                        tarDiv.style.left = '0px'
                    }else if(_x_end>=bodyW){//当最终位置在屏幕左半部分
                        tarDiv.style.left = window.screen.width - parseFloat(divW) + 'px'
                    }
                    //当元素顶部在屏幕外时
                    if(parseFloat(tarDiv.style.top)<0){
                        //置于顶部
                        tarDiv.style.top = 0
                    }
                    //当元素底部在屏幕外时
                    if(bodyH-_y_end<parseFloat(divH)/2){
                        //置于底部
                        tarDiv.style.top = bodyH-parseFloat(divH) + 'px'
                    }
                });
        // $("#id").click(function(){
        //     console.log('点击');
        // });

    </script>
</body>
</html>