拖拽效果實現方法

<!doctype html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport"          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>Document</title>    <style>        *{            margin:0;            padding:0;        }        ul{            list-style:none;        }        #box{            width:100px;            height:100px;            background:darkred;            color:white;            position: absolute;            left:0;            top:0;        }    </style></head><body><div id="box"></div><script>    var box = document.querySelector('#box');    box.addEventListener('touchstart',function(e){            // 獲取 按下時觸點的位置  尺寸1        this.size1  = e.touches[0].clientX;            // 盒子距離左邊的位置        this.size2 = box.offsetLeft;        this.size1Y = e.touches[0].clientY;        this.size2Y = box.offsetTop;    })    box.addEventListener('touchmove',function(e){        // 手指離開的 觸點的位置        this.size3 = e.touches[0].clientX;        this.size3Y = e.touches[0].clientY;        this.size4 = this.size3 - (this.size1 - this.size2)        this.size4Y = this.size3Y - (this.size1Y - this.size2Y)       //  獲取最大 left 值        var  maxLeft = document.documentElement.clientWidth - box.offsetWidth;        // 檢測水平方向值        if(this.size4  <= 0 ){            this.size4 = 0;        }        if(this.size4 > maxLeft ){            this.size4 = maxLeft;        }        // 設置 css 的 left 的值        this.style.left = this.size4+ 'px';        this.style.top = this.size4Y < 0 ? 0 : this.size4Y + 'px';    })    box.addEventListener('touchend',function(){    })    document.documentElement.addEventListener('touchstart',function(e){            e.preventDefault();    },{        passive:false    })</script></body></html>
相關文章
相關標籤/搜索