javascript實現移動端觸屏拖拽功能
更新時間:2020年07月29日 09:31:03 作者:XSP_csdn
這篇文章主要為大家詳細介紹了javascript實現移動端觸屏拖拽功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了javascript實現移動端觸屏拖拽的具體代碼,供大家參考,具體內容如下
HTML:
<body> <div id="div1"> </div> </body>
CSS:
<style media="screen"> * { margin: 0; padding: 0; } html,body { width: 100%; height:100%; } #div1 { width: 50px; height: 50px; background: cyan; position: absolute; } </style>
JS:
<script type="text/javascript"> var div1=document.querySelector('#div1'); var maxW=document.body.clientWidth-div1.offsetWidth; var maxH=document.body.clientHeight-div1.offsetHeight; div1.addEventListener('touchstart',function(e){ var ev = e || window.event; var touch = ev.targetTouches[0]; oL = touch.clientX - div1.offsetLeft; oT = touch.clientY - div1.offsetTop; document.addEventListener("touchmove",defaultEvent,false); }) div1.addEventListener('touchmove',function(e){ var ev = e || window.event; var touch = ev.targetTouches[0]; var oLeft = touch.clientX - oL; var oTop = touch.clientY - oT; if(oLeft<0){ oLeft=0; }else if (oLeft>=maxW) { oLeft=maxW; } if(oTop<0){ oTop=0; }else if (oTop>=maxH) { oTop=maxH; } div1.style.left = oLeft + 'px'; div1.style.top = oTop + 'px'; }) div1.addEventListener('touchend',function(){ document.removeEventListener("touchmove",defaultEvent); }) function defaultEvent(e) { e.preventDefault(); } </script>
說明 :
maxW:div1可移動的最大寬度
maxH:div1可移動的最大高度
oL、oT:鼠標所點位置的坐標
效果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
BootStrap Fileinput插件和Bootstrap table表格插件相結合實現文件上傳、預覽、提交的導入E
這篇文章主要介紹了BootStrap Fileinput插件和Bootstrap table表格插件相結合實現文件上傳、預覽、提交的導入Excel數據操作步驟,需要的朋友可以參考下2017-08-08