美文网首页
手机上 拖动元素

手机上 拖动元素

作者: ouxuwen | 来源:发表于2018-08-23 12:36 被阅读0次
    <!doctype html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0" name="viewport"/>
       <meta name="format-detection" content="telephone = no"/>
        <title>手机上 拖动元素 </title>
    </head>
    
    <body>
    <div id="indexbtn" style="width:100px;height:100px;background-color:black;position:absolute; "></div>
    <script>
    window.onload=function(){
        var indexbtn = document.getElementById("indexbtn");
        indexbtn.addEventListener('touchstart',touch,false);
        indexbtn.addEventListener('touchmove',touch,false);
        indexbtn.addEventListener('touchend',touch,false);
        var x,y;
        function touch(event){
            var event = event || window.event;
            switch(event.type){
                case "touchstart":
                    console.log(event.changedTouches[0]);
                    x = parseInt(event.touches[0].clientX);
                    y = parseInt(event.touches[0].clientY);
                    break;
                case "touchend":
                    console.log(event.changedTouches[0]);
                    y =  parseInt(event.changedTouches[0].clientY);
                    x = parseInt(event.changedTouches[0].clientX);
                    indexbtn.style.top = y-50+"px";//50是原始宽度一半,
                    indexbtn.style.left = x-50+"px";//50是原始高度一半,
                    break;
                case "touchmove":
                    event.preventDefault();
                    y =  parseInt(event.touches[0].clientY);
                    x = parseInt(event.touches[0].clientX);
                    indexbtn.style.top = y-50+"px";
                    indexbtn.style.left = x-50+"px";
                    break;
            }
        }
    }
    </script>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:手机上 拖动元素

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