移動(dòng)端touch事件div拖拽功能

  1. viewport
  • 如果沒有viewport,頁面上的東西會(huì)變得非常小
  1. 鼠標(biāo)事件
  • 移動(dòng)端由于點(diǎn)擊事件是多點(diǎn)的,所以event中沒有直接的clientX等等這些屬性,而是放在了event.targetTouches里
  • targetTouches和touches區(qū)別:后者有兼容問題
  1. touchmove這里,PC端把事件綁定到document上,移動(dòng)端可以直接綁在點(diǎn)擊的盒子上
  2. PC端,touchmove完了之后,即使松開鼠標(biāo)盒子也會(huì)黏住鼠標(biāo),移動(dòng)端雖然不會(huì),但是這個(gè)事件依然存在,所以應(yīng)該移除
  3. 匿名函數(shù)沒法直接移除,所以應(yīng)該把a(bǔ)ddEventListener中的函數(shù)放到外面
  4. touchend也要移除,留著沒用,鼠標(biāo)移動(dòng)時(shí)還會(huì)添一個(gè)

代碼:

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width">
        <meta charset="utf-8">
        <title></title>
        <style>
            .box{width: 200px;height: 200px;background: #ccc;position: absolute;top: 0;left: 0;}
        </style>
        <script>
            window.onload = function(){
                let oBox = document.getElementsByClassName('box')[0]

                oBox.addEventListener('touchstart',function(event){
                    let disX = event.targetTouches[0].clientX-oBox.offsetLeft
                    let disY = event.targetTouches[0].clientY-oBox.offsetTop

                    function fnMove(event){
                        oBox.style.left = event.targetTouches[0].clientX - disX + 'px'
                        oBox.style.top = event.targetTouches[0].clientY - disY + 'px'
                    }
                    function fnEnd(){
                        oBox.removeEventListener('touchmove',fnMove,false)
                        oBox.removeEventListener('touchend',fnEnd,false)
                    }

                    oBox.addEventListener('touchmove',fnMove,false)
                    oBox.addEventListener('touchend',fnEnd,false)
                },false)
            }
        </script>
    </head>
    <body>
        <div class="box">

        </div>
    </body>
</html>

效果:


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容