Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

เหตุการณ์ touchmove ของ HTML DOM

เหตุการณ์ touchmove ของ HTML DOM จะถูกกระตุ้นเมื่อ นิ้วมือถูกเลื่อนข้ามหน้าจอสัมผัส

หมายเหตุ: เหตุการณ์นี้ทำงานได้เฉพาะบนอุปกรณ์ที่มีหน้าจอสัมผัสเท่านั้น

ไวยากรณ์ (Syntax)

ใน HTML

ontouchmove = "eventFunction()"

ใน JavaScript

eventObject.ontouchmove = eventFunction

หมายเหตุ: ตัวอย่าง Touch event ถูกทดสอบบน HTML Editor ออนไลน์ที่เข้าถึงผ่านมือถือหรืออุปกรณ์ที่รองรับการสัมผัส

ตัวอย่างการใช้งาน

ตัวอย่างเกมเลื่อนนิ้ว: เริ่มเกมแล้วเลื่อนนิ้วอยู่ในพื้นที่สีเขียว (ปลอดภัย) หากเลื่อนถึงจุดสิ้นสุด (x === 439) จะชนะ หากเลื่อนเข้าพื้นที่สีแดง (อันตราย) จะแพ้

<!DOCTYPE html>
<html>
<head>
<title>HTML DOM touchmove event</title>
<style>
  * { padding: 2px; margin:5px; }
  form { width:70%; margin: 0 auto; text-align: center; }
  #outer { width:70%; margin: 0 auto; padding: 0; text-align: center; border:1px solid black; height: 105px; background-color: #28a745; }
  input[type="button"] { border-radius: 10px; }
  #upper { border-bottom: 1px solid black; height: 40px; margin: 0 0 15px 0; background-color: #DC3545; }
  #lower { border-top: 1px solid black; height: 40px; margin: 15px 0 0 0; background-color: #DC3545; }
</style>
</head>
<body>
  <form>
    <fieldset>
      <legend>HTML DOM touchmove event</legend>
      <div id="outer">
        <div id="upper"><h2>Danger</h2></div>
        <div id="lower"><h2>Danger</h2></div>
      </div>
      <input type="button" id="start" value="Start" onclick="gameStart()">
      <div id="divDisplay"></div>
    </fieldset>
  </form>
<script>
  var divDisplay = document.getElementById('divDisplay');
  var gameDisplay = document.getElementById('outer');
  function playGame(event) {
    var x = event.touches[0].clientX;
    var y = event.touches[0].clientY;
    if(y > 95 && y < 110){
      divDisplay.textContent = 'Keep Going!';
      if(x === 439){
        divDisplay.textContent = 'Congrats! You Did it!';
        gameDisplay.removeEventListener('touchmove', playGame);
      }
    }
    else{
      divDisplay.textContent = 'You moved to DANGER area. You loose!';
      gameDisplay.removeEventListener('touchmove', playGame);
    }
  }
  function gameStart(){
    gameDisplay.addEventListener('touchmove',playGame);
  }
</script>
</body>
</html>

ผลลัพธ์ (Output)

หลังกด "Start" และเลื่อนนิ้วอยู่ในพื้นที่สีเขียว (ปลอดภัย):

เหตุการณ์ touchmove ของ HTML DOM

หลังกด "Start" และเลื่อนนิ้วถึงจุดสิ้นสุดพื้นที่สีเขียว:

เหตุการณ์ touchmove ของ HTML DOM

หลังกด "Start" และเลื่อนนิ้วเข้าพื้นที่สีแดง (อันตราย):

เหตุการณ์ touchmove ของ HTML DOM