溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

利用JavaScript如何在移動端實現(xiàn)一個拖動元素

發(fā)布時間:2020-11-25 14:45:11 來源:億速云 閱讀:128 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)利用JavaScript如何在移動端實現(xiàn)一個拖動元素,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

代碼實現(xiàn):

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    body {
      background-color: #1cee89;
    }
    
    div {
      position: absolute;
      left: 0;
      width: 100px;
      height: 100px;
      background-color: #8294ff;
      border-radius: 20px;
    }
  </style>
</head>

<body>
  <div></div>
  <script>
    var div = document.querySelector('div');
    var startX = 0; // 獲取手指初始坐標(biāo)
    var startY = 0;
    var x = 0; // 獲得盒子原來的位置
    var y = 0;
    // 手指觸摸
    div.addEventListener('touchstart', function(e) {
      // 獲取手指初始坐標(biāo)
      startX = e.targetTouches[0].pageX;
      startY = e.targetTouches[0].pageY;
      x = this.offsetLeft;
      y = this.offsetTop;
      this.style.boxShadow = '0 0 15px rgba(0, 0, 0, .6)';
    });
    // 手指離開
    div.addEventListener('touchend', function(e) {
      this.style.boxShadow = '';
    });

    // 手指按住移動
    div.addEventListener('touchmove', function(e) {
      // 計算手指的移動距離:手指移動之后的坐標(biāo)減去手指初始的坐標(biāo)
      var moveX = e.targetTouches[0].pageX - startX;
      var moveY = e.targetTouches[0].pageY - startY;
      // 移動盒子 盒子原來的位置 + 手指移動的距離
      this.style.left = x + moveX + 'px';
      this.style.top = y + moveY + 'px';
      e.preventDefault(); // 阻止屏幕滾動的默認(rèn)行為
    });
  </script>
</body>

</html>

關(guān)于利用JavaScript如何在移動端實現(xiàn)一個拖動元素就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI