Computer >> 컴퓨터 >  >> 프로그래밍 >> HTML

HTML DOM touchstart 이벤트 완벽 가이드: 터치 시작 이벤트의 개념과 활용법

HTML DOM의 touchstart 이벤트는 사용자가 터치 스크린을 손가락으로 접촉하는 순간 발생하는 이벤트입니다. 모바일 웹 개발에서 터치 기반 인터랙션을 구현할 때 필수적으로 사용되는 이벤트입니다.

참고: touchstart 이벤트는 터치 스크린이 장착된 기기(스마트폰, 태블릿 등)에서만 동작합니다. 일반 데스크톱 환경에서는 마우스 클릭 이벤트(click, mousedown)를 대신 사용해야 합니다.

touchstart 이벤트 문법

HTML에서 직접 지정하기

ontouchstart = "eventFunction()"

JavaScript에서 할당하기

eventObject.ontouchstart = eventFunction

참고: 터치 이벤트 예제는 모바일 기기 또는 터치 입력이 가능한 시스템에서 접속한 온라인 HTML 에디터를 통해 실행해야 합니다. 화면을 2초간 길게 누르는 것과 같은 실제 터치 조작이 필요하기 때문입니다.

touchstart 이벤트 활용 예제

다음은 touchstart 이벤트를 활용한 간단한 게임 예제입니다. 버튼을 1초간 누르고 있으면 승리하는 방식입니다.

예제 코드

<!DOCTYPE html>
<html>
<head>
<title>HTML DOM touchstart event</title>
<style>
    form {
        width:70%;
        margin: 0 auto;
        text-align: center;
    }
    * {
        padding: 2px;
        margin:5px;
    }
    input[type="button"] {
        border-radius: 50%;
        font-size: 20px;
        padding: 20px;
        border: 5px solid rgb(220, 53, 69);
        background: rgba(220, 53, 69, 0.5);
        color: #fefefe;
    }
</style>
</head>
<body>
    <form>
        <fieldset>
            <legend>HTML-DOM-touchstart-event</legend>
            <label for="textSelect">Game Time</label>
            <input type="button" id="gameSelect" value="Hold On">
            <div id="divDisplay">Hold On for 1 - sec to Win</div>
        </fieldset>
    </form>
<script>
    var divDisplay = document.getElementById("divDisplay");
    var gameSelect = document.getElementById("gameSelect");
    var duration = 1000;
    var timer;
    gameSelect.ontouchstart = startEventAction;
    function startEventAction() {
        timer = setTimeout(victory, duration);
    }
    gameSelect.ontouchend = endEventAction;
    function endEventAction(){
        if(timer)
            clearTimeout(timer);
    }
    function victory(){
        divDisplay.textContent = "You Win"
    }
</script>
</body>
</html>

코드 설명

위 예제의 동작 원리는 다음과 같습니다.

1. touchstart 발생 시: 사용자가 'Hold On' 버튼에 손가락을 대는 순간 startEventAction 함수가 실행되어 1초(1000ms) 후 승리 처리를 하는 타이머가 시작됩니다.
2. touchend 발생 시: 손가락을 떼면 endEventAction 함수가 실행되어 아직 1초가 지나지 않았다면 타이머가 취소됩니다.
3. 승리 조건: 정확히 1초간 터치를 유지하면 victory 함수가 호출되어 화면에 'You Win' 메시지가 표시됩니다.

실행 결과

'Hold On' 버튼을 터치하기 전:

HTML DOM touchstart 이벤트 완벽 가이드: 터치 시작 이벤트의 개념과 활용법

'Hold On' 버튼을 터치한 후:

HTML DOM touchstart 이벤트 완벽 가이드: 터치 시작 이벤트의 개념과 활용법

정리

touchstart 이벤트는 터치 기기에서 손가락이 화면에 닿는 즉시 반응해야 하는 UI를 만들 때 유용합니다. 특히 게임 버튼, 드래그 앤 드롭, 길게 누르기(long press) 제스처 구현 등에 널리 활용되며, ontouchend, ontouchmove, ontouchcancel 같은 다른 터치 이벤트와 함께 사용하면 더욱 완성도 높은 터치 인터랙션을 구현할 수 있습니다.