상세 컨텐츠

본문 제목

[JavaScript] 자바스크립트 브라우저 터치 이벤트 (터치스크린, 모바일터치스키린 등등) 이벤트 관련

WEB/JavaScript

by AlrepondTech 2017. 11. 22. 14:40

본문

반응형
728x170

 

 

 

 

=================================

=================================

=================================

 

 

 

 

 

 

 

출처: https://m.blog.naver.com/PostView.nhn?blogId=b_feather&logNo=50117082290&proxyReferer=https%3A%2F%2Fwww.google.co.kr%2F

 

 

대부분의 사용자가 모바일 환경이 아닌 일반적인 PC web 인터페이스로 웹서비스에 접속하던 시절에는 방문자의 브라우저와 운영체제만 감지를 하면 대부분의 문제를 해결할 수 있었지만, 태블릿과 스맛폰이 많이 보급되면서 크로스브라우징 뿐만 아니라 어떤 기기로 접속했느냐에 따라 각각 처리와 대응을 따로 해줄 필요가 생겼습니다. 이러한 문제를 해결하기 위해 구글링을 하면서 알아낸 것들을 바탕으로 터치 이벤트 환경 및 접속 기기를 감지해주는 자바스크립트 함수를 짜봤습니다.

 

함수의 대략적인 흐름은 다음과 같습니다:

createTouch 생성이 가능한지 확인하여 터치 이벤트 가용 환경인지 확인.

navigator.userAgent 속성을 이용해 접속기기가 아이폰인지 안드로이드폰인지 확인.

1, 2의 결과에 따라 "iPhone", "Android", "true", "false" 리턴.

 

 

function verifyTouch()

{

var verification=false; //결과값 초기 설정

if ("createTouch" in document)

{

//createTouch 생성이 가능한지 확인

verification=true;

}

var device=navigator.userAgent.toLowerCase();

//navigator.userAgent 소문자화

if(device.indexOf("iphone")!=-1)

{

//아이폰인지 확인

verification="iPhone";

}

else if(device.indexOf("android")!=-1)

{

//안드로이드폰인지 확인

verification="Android";

}

return verification; //결과값 반환

}

 

주의: 본 코드는 모든 환경에서 테스트된 것은 아닙니다.

필요하신 용도에 맞게 수정해서 사용하시기 바랍니다.

 

 

 

 

=================================

=================================

=================================

 

 

 

 

출처: [자바스크립트] 접속 디바이스 체크 (데스크톱인지 모바일인지)

출처: 

http://myeonguni.tistory.com/1396

 [명우니닷컴]

 

 

[자바스크립트] 브라우저 종류 및 버전 체크

 

작업 내역 : 접속자의 디바이스를 체크하여 마우스 이벤트를 지원할지 터치 이벤트를 지원할지 판단하기 위하여

 

소스 코드

 

		//@ myeonguni.com @ 		// 접속 디바이스를 확인합니다(데스크탑:false, 모바일:true) 		function isTouchAble(){  			if(navigator.userAgent.indexOf('Mobile') != -1){ return true; } 			else{ return false; }  		} 

 

 

위에서 작성한 함수 사용 예)

 

		// 터치 지원 여부 		var touchAble = isTouchAble();  		// 디바이스에 따른 이벤트를 선택합니다. 		var START_EV = (touchAble) ? 'touchstart' : 'mousedown';  		var MOVE_EV = (touchAble) ? 'touchmove' : 'mousemove';  		var END_EV = (touchAble) ? 'touchend' : 'mouseup';  		var BSTART_EV = (touchAble) ? 'touchcancel' : 'mouseover'; 

 



출처: http://myeonguni.tistory.com/1396 [명우니닷컴]

 

 

=================================

=================================

=================================

 

 

 

출처: http://yjcorp.tistory.com/19

 

[Javascript] 터치 디바이스 지원 확인

 

if('ontouchstart' in document.documentElement){

    alert("touch device");

}else{

    alert("not touch device");

}

 

 

 

=================================

=================================

=================================

 

 

 

 

출처: https://developer.mozilla.org/ko/docs/Web/API/Touch_events

 

 

일부분만 번역함.
 

 터치를 기반으로 한 양질의 서비스를 제공하기 위해, Touch Events(터치이벤트)는 터치로 인한 움직임을 감지할 능력을 제공합니다.

터치 이벤트 인터페이스는 상대적으로 low-lever API이며 multi-touch interaction등의 다양한 동작을 특정해 트리거 할 수 있습니다. multi-touch interaction은 한 손가락이 터치패드에 처음 닫는 순간 시작합니다. 이후 다른 손가락들이 터치패드에 닿고 선택적으로 터치패드를 가로지를 수도 있습니다. interaction은 손가락들이 터치패드에서 떨어지면 끝납니다. interaction동안에 어플리케이션은 touch start, move, end 이벤트들을 받습니다.

Touch events는 동시에 여러 손가락으로 동시에 혹은 여러 지점에 터치 할 수 있다는 것만 제외하면 마우스 이벤트와 유사합니다. 터치이벤트 인터페이스는 현재 액션과 터치 지점을 캡슐화 합니다. single touch로 대표되는 interface는 터치된 정보등을 포함합니다.

DefinitionsEdit

Surface
터치 스크린, 터치 패드등을 포함합니다.
Touch point
손가락이나 터치 펜을 이용해 터치한 지점을 말합니다.

InterfacesEdit

TouchEvent
터치나 surface 위에서의 움직임들 입니다.
Touch
touch surface위의 한 지점에 접촉할 때 발생합니다.
TouchList
다중의 터치가 동시에 일어 났을 때 발생합니다.

ExampleEdit

This example tracks multiple touch points at a time, allowing the user to draw in a <canvas> with more than one finger at a time. It will only work on a browser that supports touch events.

Note: The text below uses the term "finger" when describing the contact with the surface, but it could, of course, also be a stylus or other contact method.

Create a canvas

<canvas id="canvas" width="600" height="600" style="border:solid black 1px;">   Your browser does not support canvas element. </canvas> <br> <button onclick="startup()">Initialize</button> <br> Log: <pre id="log" style="border: 1px solid #ccc;"></pre>

Setting up the event handlers

When the page loads, the startup() function shown below should be called by our <body> element's onload attribute (but in the example we use a button to trigger it, due to limitations of the MDN live example system).

function startup() {   var el = document.getElementsByTagName("canvas")[0];   el.addEventListener("touchstart", handleStart, false);   el.addEventListener("touchend", handleEnd, false);   el.addEventListener("touchcancel", handleCancel, false);   el.addEventListener("touchmove", handleMove, false);   log("initialized."); }

This simply sets up all the event listeners for our <canvas> element so we can handle the touch events as they occur.

Tracking new touches

We'll keep track of the touches in-progress.

var ongoingTouches = [];

When a touchstart event occurs, indicating that a new touch on the surface has occurred, the handleStart() function below is called.

function handleStart(evt) {   evt.preventDefault();   log("touchstart.");   var el = document.getElementsByTagName("canvas")[0];   var ctx = el.getContext("2d");   var touches = evt.changedTouches;            for (var i = 0; i < touches.length; i++) {     log("touchstart:" + i + "...");     ongoingTouches.push(copyTouch(touches[i]));     var color = colorForTouch(touches[i]);     ctx.beginPath();     ctx.arc(touches[i].pageX, touches[i].pageY, 4, 0, 2 * Math.PI, false);  // a circle at the start     ctx.fillStyle = color;     ctx.fill();     log("touchstart:" + i + ".");   } }

This calls event.preventDefault() to keep the browser from continuing to process the touch event (this also prevents a mouse event from also being delivered). Then we get the context and pull the list of changed touch points out of the event's TouchEvent.changedTouches property.

After that, we iterate over all the Touch objects in the list, pushing them onto an array of active touch points and drawing the start point for the draw as a small circle; we're using a 4-pixel wide line, so a 4 pixel radius circle will show up neatly.

Drawing as the touches move

Each time one or more fingers moves, a touchmove event is delivered, resulting in our handleMove() function being called. Its responsibility in this example is to update the cached touch information and to draw a line from the previous position to the current position of each touch.

function handleMove(evt) {   evt.preventDefault();   var el = document.getElementsByTagName("canvas")[0];   var ctx = el.getContext("2d");   var touches = evt.changedTouches;    for (var i = 0; i < touches.length; i++) {     var color = colorForTouch(touches[i]);     var idx = ongoingTouchIndexById(touches[i].identifier);      if (idx >= 0) {       log("continuing touch "+idx);       ctx.beginPath();       log("ctx.moveTo(" + ongoingTouches[idx].pageX + ", " + ongoingTouches[idx].pageY + ");");       ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY);       log("ctx.lineTo(" + touches[i].pageX + ", " + touches[i].pageY + ");");       ctx.lineTo(touches[i].pageX, touches[i].pageY);       ctx.lineWidth = 4;       ctx.strokeStyle = color;       ctx.stroke();        ongoingTouches.splice(idx, 1, copyTouch(touches[i]));  // swap in the new touch record       log(".");     } else {       log("can't figure out which touch to continue");     }   } }

This iterates over the changed touches as well, but it looks in our cached touch information array for the previous information about each touch in order to determine the starting point for each touch's new line segment to be drawn. This is done by looking at each touch's Touch.identifier property. This property is a unique integer for each touch, and remains consistent for each event during the duration of each finger's contact with the surface.

This lets us get the coordinates of the previous position of each touch and use the appropriate context methods to draw a line segment joining the two positions together.

After drawing the line, we call Array.splice() to replace the previous information about the touch point with the current information in the ongoingTouches array.

Handling the end of a touch

When the user lifts a finger off the surface, a touchend event is sent. We handle both of these the same way: by calling the handleEnd()function below. Its job is to draw the last line segment for each touch that ended and remove the touch point from the ongoing touch list.

function handleEnd(evt) {   evt.preventDefault();   log("touchend");   var el = document.getElementsByTagName("canvas")[0];   var ctx = el.getContext("2d");   var touches = evt.changedTouches;    for (var i = 0; i < touches.length; i++) {     var color = colorForTouch(touches[i]);     var idx = ongoingTouchIndexById(touches[i].identifier);      if (idx >= 0) {       ctx.lineWidth = 4;       ctx.fillStyle = color;       ctx.beginPath();       ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY);       ctx.lineTo(touches[i].pageX, touches[i].pageY);       ctx.fillRect(touches[i].pageX - 4, touches[i].pageY - 4, 8, 8);  // and a square at the end       ongoingTouches.splice(idx, 1);  // remove it; we're done     } else {       log("can't figure out which touch to end");     }   } }

This is very similar to the previous function; the only real differences are that we draw a small square to mark the end and that when we call Array.splice(), we simply remove the old entry from the ongoing touch list, without adding in the updated information. The result is that we stop tracking that touch point.

Handling canceled touches

If the user's finger wanders into browser UI, or the touch otherwise needs to be canceled, the touchcancel event is sent, and we call the handleCancel() function below.

function handleCancel(evt) {   evt.preventDefault();   log("touchcancel.");   var touches = evt.changedTouches;      for (var i = 0; i < touches.length; i++) {     var idx = ongoingTouchIndexById(touches[i].identifier);     ongoingTouches.splice(idx, 1);  // remove it; we're done   } }

Since the idea is to immediately abort the touch, we simply remove it from the ongoing touch list without drawing a final line segment.

Convenience functions

This example uses two convenience functions that should be looked at briefly to help make the rest of the code more clear.

Selecting a color for each touch

In order to make each touch's drawing look different, the colorForTouch() function is used to pick a color based on the touch's unique identifier. This identifier is an opaque number, but we can at least rely on it differing between the currently-active touches.

function colorForTouch(touch) {   var r = touch.identifier % 16;   var g = Math.floor(touch.identifier / 3) % 16;   var b = Math.floor(touch.identifier / 7) % 16;   r = r.toString(16); // make it a hex digit   g = g.toString(16); // make it a hex digit   b = b.toString(16); // make it a hex digit   var color = "#" + r + g + b;   log("color for touch with identifier " + touch.identifier + " = " + color);   return color; }

The result from this function is a string that can be used when calling <canvas> functions to set drawing colors. For example, for a Touch.identifier value of 10, the resulting string is "#aaa".

Copying a touch object

Some browsers (mobile Safari, for one) re-use touch objects between events, so it's best to copy the bits you care about, rather than referencing the entire object.

function copyTouch(touch) {   return { identifier: touch.identifier, pageX: touch.pageX, pageY: touch.pageY }; }

Finding an ongoing touch

The ongoingTouchIndexById() function below scans through the ongoingTouches array to find the touch matching the given identifier, then returns that touch's index into the array.

function ongoingTouchIndexById(idToFind) {   for (var i = 0; i < ongoingTouches.length; i++) {     var id = ongoingTouches[i].identifier;          if (id == idToFind) {       return i;     }   }   return -1;    // not found }

Showing what's going on

function log(msg) {   var p = document.getElementById('log');   p.innerHTML = msg + "\n" + p.innerHTML; }

If your browser supports it, you can see it live.

jsFiddle example

Additional tipsEdit

This section provides additional tips on how to handle touch events in your web application.

Handling clicks

Since calling preventDefault() on a touchstart or the first touchmove event of a series prevents the corresponding mouse events from firing, it's common to call preventDefault() on touchmove rather than touchstart. That way, mouse events can still fire and things like links will continue to work. Alternatively, some frameworks have taken to refiring touch events as mouse events for this same purpose. (This example is oversimplified and may result in strange behavior. It is only intended as a guide.)

function onTouch(evt) {   evt.preventDefault();   if (evt.touches.length > 1 || (evt.type == "touchend" && evt.touches.length > 0))     return;    var newEvt = document.createEvent("MouseEvents");   var type = null;   var touch = null;    switch (evt.type) {     case "touchstart":        type = "mousedown";       touch = evt.changedTouches[0];       break;     case "touchmove":       type = "mousemove";       touch = evt.changedTouches[0];       break;     case "touchend":               type = "mouseup";       touch = evt.changedTouches[0];       break;   }    newEvt.initMouseEvent(type, true, true, evt.originalTarget.ownerDocument.defaultView, 0,     touch.screenX, touch.screenY, touch.clientX, touch.clientY,     evt.ctrlKey, evt.altKey, evt.shiftKey, evt.metaKey, 0, null);   evt.originalTarget.dispatchEvent(newEvt); }

Calling preventDefault() only on a second touch

One technique for preventing things like pinchZoom on a page is to call preventDefault() on the second touch in a series. This behavior is not well defined in the touch events spec, and results in different behavior for different browsers (i.e., iOS will prevent zooming but still allow panning with both fingers; Android will allow zooming but not panning; Opera and Firefox currently prevent all panning and zooming.) Currently, it's not recommended to depend on any particular behavior in this case, but rather to depend on meta viewport to prevent zooming.

 

 

=================================

=================================

=================================

 

 

현재 자신의 터치 위치 알아내기

 

다른 터치이벤트 "touchstart", "touchend", "touchcancel" 등등에도 아래와 비슷하게 적용하면 된다.

 

  this.getGLT.domElement.addEventListener('touchmove',

                function f(evt)

                {

                    event.preventDefault(); //해당이벤트 발생시 패이지에 이벤트가 가는걸 막는다.

                    let touches = evt.touches;

                    let touch1 = touches[0];

 

                    //캔버스나 다른 변수가 있을떄에는 domelement 대신 캔버스 변수나 다른변수로 넣어주면 된다.

                    let x = touch1.pageX - domElement.offsetLeft;

                    let y = touch1.pageY - domElement.offsetTop;

                     

                    //code

                    //....

                    //....

 

                }, false);

 

 

 

=================================

=================================

=================================

 

 

 

출처: http://www.freeimage.kr/iphone/64

 

 

 

Android 또는 iOS을 사용하면 Javascript의 mousedown, mouseup, mousemove같은 이벤트를 그대로 사용할 수 없다.  터치스크린은 마우스가 아니기때문이다. Android와 iOS는 새로운 Javascript touch events API를 지원함으로서 Javascript가 터치스크린을 원할하게 사용 할 수 있도록 하고 있다.

Touche events
  • touchstart : 손이 터치스크린의 닫는 순간 발생
  • touchend : 손이 터치스크린에서 떨어지는 순간 발생 (iOS의 경우 touchcancel이벤트 발생)
  • touchmove : 손을 터치한상태로 터치스크린을 이동하면 발생
  • touchcancel : iOS에서 touchend의 또다른 이름 인것 같다.
터치스크린은 단순한 터치 뿐만 아니라 멀티터치라는 또다른 제스쳐를 사용 할 수 있다. 이를 위해 Javascript는 Gesture events API또한 제공하고 있다. 하지만 안타깝게도 Android에서는 Gesture events API를 지원하지 않는다고 한다.
Gesture events
  • gesturestart : 멀티 터치 시작
  • gesturechange : 멀티 터치상태로 이동
  • gestureend : 멀티 터치 종료
 
 Example :
 function touch(event){   alert(event.touches.length); } document.addEventListener('touchstart', touch, false);

 

 

 

=================================

=================================

=================================

 

 

출처: http://www.bsidesoft.com/?p=285

 

 

마우스 이벤트는 매우 심각하게 다뤄온지 오래되었기 때문에 여러가지 기법이 널리 알려져있습니다. 이에 반해 터치이벤트는 손쉽게 정리하기 쉽지 않습니다.

터치이벤트는 더 이상 모바일 기기만의 문제가 아닙니다. 반응형 웹을 구성할 때 마우스 조차 터치의 슬라이드를 흉내내야하고 터치패널이 내장된 윈도우 기기도 심심치 않게 있습니다.

터치이벤트를 깊이 들여다보고, 보다 손쉽게 사용할 방법을 생각해 보겠습니다.

 
 
 

 

터치이벤트의 문제top

기본은 터치이벤트라 불리는 이벤트의 종류입니다. 현재 대부분의 모바일 기기에서 지원되는 이벤트는 3가지로 그 외에는 벤더의 의존성이 너무 심해서 범용으로 쓰기는 무리가 있습니다.

  • touchstart : 손가락을 화면에 닿는 순간 발생
  • touchmove : touchstart 한 상태에서 떼지 않고 화면을 움직여 다닐 때 주기적으로 발생
  • touchend : 손가락을 화면에서 떼면 발생

느낌으로 보자면 mousedown, mousemove, mouseup 과 같은 분위기 입니다…만!

터치이벤트는 중요한 차이점이 있습니다. 멀티터치를 지원한다는 거죠.

  1. 예를 들어 검지가 화면에 닿는 순간 이미 touchstart 가 발생했습니다.
  2. 하지만 그 상태에서 중지가 화면에 닿으면 touchend가 발생한 적도 없이 또 touchstart가 발생합니다.
  3. 마찬가지로 검지를 움직이면서 중지를 떼면 touchmove가 발생하면서 동시에 touchend도 발생합니다.

이 점이 바로 지옥입니다.

손가락이 여러 개다 보니 하면서 ~ 한다는 거죠. 이런 관점으로 마우스 이벤트를 새삼 바라보면 손가락을 한 개만 지원하는 프로요같은 싱글 터치기반의 이벤트와 비슷한 것입니다.

단순히 dom 에 터치이벤트를 거는 것 만으로는 복잡한 처리를 할 수 없습니다. touchstart 가 수신 되어도 모든 손가락이 touchstart 가 아니고 어떤 손가락은 touchmove 중이고, 어떤 손가락은 이미 touchstart 가 발생된 상태이기 때문입니다.

이를 테스트하기 위한 간단한 js를 제작해 봅시다.

  1. div 를 하나 설정하고 id 를 test 로 준다.
  2. touchstart, touchend 를 걸어 결과를 test.innerHTML 을 통해 보여준다.
  3. 별도의 로그함수를 작성하여 간단히 사용한다.

로그함수를 작성해봅시다. div는 공간이 유한하므로 10개 정도 보이다가 다시 클리어하고 보여주는 식으로 가겠습니다.

<div style=”width:100%;height:480px;background:#ff0;color:#000;font-size:9px” id=”test”>
</div>
var test = document.getElementById( "test" );
var logCount = 0;
 
function log( $v ){
  if( ++logCount > 10 ){
    logCount = 0;
    test.innerHTML = $v + "<br>";
  }else{
    test.innerHTML += $v + "<br>";
  }
}

다음은 이벤트 리스너에서의 작동인데 배열에 필요한 내용을 차곡히 넣은 뒤 join( ” ) 을 통해 log 로 쏴주면 될 것입니다.
터치된 객체 자체는 touches 에 들어있지만 touchend 의 경우는 changedTouches 를 조사해야 하니 두 개 다 정리해서 보여주도록 하겠습니다.

function touchListener( $e ){
  var i, j, t0, touch;
 
  //touches부터 정리
  touch = $e.touches;
  t0 = [ '<b>',
    $e.type,
    '</b><br>touches(length:',
    j = touch.length
  ];
 
  for( i = 0 ; i < j ; i++ )
    t0.push(
      ', ', i, ':',
      parseInt( touch[i].pageX ), ',',
      parseInt( touch[i].pageY )
    );
 
  //changedTouches 정리
  touch = $e.changedTouches;
  t0.push(
    ')<br> changed(length:',
    j =touch.length
  );
  for( i = 0 ; i < j ; i++ )
    t0.push(
      ', ', i, ':',
      parseInt( touch[i].pageX ), ',',
      parseInt( touch[i].pageY )
    );
 
  //로그에 보고
  log( t0.join( '' ) + ')' );
  test.dispatchEvent( new Event("to") );
}

다 되었으니 이제 이벤트 리스너만 걸어주면 됩니다.

test.addEventListener( 'touchstart', touchListener );
test.addEventListener( 'touchend', touchListener );

다음과 같은 로그들이 찍혀 나오기 시작할 겁니다.

 

 
 
 

 

touchmove의 특이점top

touchmove 는 touchstart 나 touchend 와 달리 일반적으로 브라우저가 처음부터 소유해 버립니다.

따라서 최초 한 번은 발생하지만 그 이후는 브라우저의 스크롤이 가져가 버립니다.

만약 어떤 dom 에서 touchmove 이벤트를 사용하겠다는 뜻은 바꿔 말하면

그 영역에서는 스크롤이 안일어나게 하겠다

는 뜻입니다.

따라서 touchmove 의 경우는 반드시 e.preventDefault() 를 호출하여 막아주지 않으면 제대로 작동하지 않습니다. 이러한 특이점을 머리 속에 염두해두고 귀찮으므로, 대부분의 실험은 touchstart 와 touchend 를 이용하는 쪽으로 가겠습니다.

 
 
 

 

Touches와 changedTouchestop

이제 이 테스터를 갖고 놀다보면 어떤 식으로 터치를 처리해야 하는 지 감이 옵니다. 터치이벤트는 touches 배열과 changedTouches 배열의 미묘한 조합인 것입니다. 이 중 changedTouches 를 먼저 이해해 보죠.

  1. 우선 검지를 화면에 가져갑시다.touchstart
    touches(length:1,0:100,100)
    changed(length1,0:100,100)
  2. 즉 터치된 것도 변화가 일어난 것도 각각 1개이고 그 둘은 같은 거죠.
     
  3. 그 상태에서 움직이지 않고 중지도 화면에 가져갑니다.touchstart
    touches(length:1,0:100,100, 1:200,200)
    changed(length1,0:200,200)
  4. 0번은 유지 되지만 1번이 새롭게 터치 객체에 추가됩니다. 이 때 변화한 손가락 쪽은 중지로 changed에는 중지만 들어와 있습니다.
     
  5. 검지를 떼봅시다.touchend
    touches(length:1,0:200,200)
    changed(length1,0:100,100)
  6. 화면에 남아있는 중지가 touches의 0번이 되고 방금 뗀 검지는 changed의 0번이 되어 들어옵니다.
     
  7. 중지도 뗍니다.touchend
    touches(length:0)
    changed(length1,0:200,200)
  8. touches는 더 이상 남아있지 않고 중지는 changed의 0번이 되어 들어옵니다.

우선 위의 실험에서 알 수 있는 것은…

  • touchstart 와 touchend 에서 changedTouches 는 언제나 1개만 들어옵니다.
  • changedTouches 가 여러 개 들어오는 상황은 touchmove 에서 2개 이상의 손가락을 동시에 움직일 때 입니다.
  • 인덱스는 그냥 인덱스일 뿐 처음 터치한 손가락이 뭔지, 두 번째 터치한 손가락이 뭔지를 알려주지는 않습니다.

 
 
 

 

identifier 를 이용한 손가락별 이벤트top

그렇습니다. touches 의 배열과 changedTouches 의 배열을 굴려봐야 거기의 인덱스로는 아무 것도 알 수 없습니다.
각 터치 객체에는 identifier 라는 손가락 고유의 id 를 갖고 있습니다. 바로 이것을 이용해야 합니다.

잠시 마우스 이벤트로 돌아가 봅시다.

  1. 마우스 이벤트를 싱글터치 이벤트로 이해할 수도 있지만 아주 정확하게 말하자면 마우스 왼쪽 버튼에 한정된 이벤트로 볼 수도 있습니다.
  2. 그렇다면 터치이벤트도 손가락별 이벤트로 나눌 수 있습니다.
    단지 검지이벤트로 할 수는 없고 1번째 손가락 이벤트, 2번째 손가락 이벤트 등으로 처리할 수 있습니다.

이 아이디어를 적용하려면 dom 의 이벤트를 받는 리스너가 손가락별 이벤트의 라우터로 작동하여 다시 이벤트를 전달해줘야 합니다. 이러한 이벤트를 매우 상세하게 정의해보면 다음과 같이 생각할 수 있습니다(네개까지만 하겠습니다 =.=; )

touchstart0, touchmove0, touchend0
touchstart1, touchmove1, touchend1
touchstart2, touchmove2, touchend2
touchstart3, touchmove3, touchend3

또한 앞에서 한 실험을 고려해보면 개별 손가락 이벤트로 처리하는 이상 변화된 손가락만 인지하면 되므로 touches 를 무시하고 changedTouches 만 사용하면 됩니다.

모든 내용을 바탕으로 우선 터치이벤트를 라우팅 해 줄 리스너를 작성해봅시다.

function touchRouter( $e ){
  var t, e, i, j, k;
 
  //앞 서 설명한대로, move 일 땐 막자.
  if( $e.type == "touchmove" ) $e.preventDefault();
 
  t = $e.changedTouches;
  for( i = 0, j = t.length ; i < j ; i++ ){
 
    //id를 붙여 이벤트를 만들고
    e = document.createEvent( "Event" );
    e.initEvent( $e.type + t[i].identifier, truetrue );
 
    //속성을 복사해준다.
    for( k in t[i] ) e[k] = t[i][k];
 
    //라우팅~
    $e.target.dispatchEvent( e );
  }
}

머..딱히 설명할 것도 없습니다. 그냥 라우팅 하고 있습니다. 이제 손가락별로 이벤트를 걸어봅시다. 순서는 test 에 라우터를 걸어준 뒤, 손가락별 이벤트를 셋팅하면 됩니다. 손가락별 리스너를 먼저 작성해볼까요.

function fingerListener( $e ){
  log(
    '<b>' + $e.type +
    '</b><br>pos(' +
    parseInt( $e.pageX ) + ',' +
    parseInt( $e.pageY ) +
    ')'
  );
}

이제 test 에 위에 언급한 순서대로 걸어줍니다.

//라우터 셋팅
test.addEventListener( 'touchstart', touchRouter );
test.addEventListener( 'touchmove', touchRouter );
test.addEventListener( 'touchend', touchRouter );
 
//0번손가락
test.addEventListener( 'touchstart0', fingerListener );
test.addEventListener( 'touchend0', fingerListener );
 
//1번손가락
test.addEventListener( 'touchstart1', fingerListener );
test.addEventListener( 'touchend1', fingerListener );

이제 다음과 같은 화면을 볼 수 있습니다.

 

성능 상의 개선이라면 이벤트객체를 매번 생성치 말고 풀링하는 방안과 for~in 루프 대신 touch같은 속성에 직접 touches객체를 넣어서 전달해주는 방법 등을 고려해볼만 합니다.

 


 
 

반응형
 
 
 
728x90

 

결론top

이게 정말 끝이라고 생각하신건 아니겠죠? 모바일 개발의 지옥은 지금부터 입니다.

현재 일반적으로 커버해야하는 모바일 브라우저의 수는 국내처럼 갤럭시로 대동통합된 경우를 봐도 20개 이상입니다. 20개?!! 정말? 주요한 것들만 세봅니다.

  • 아이폰, 아이패드용 : 16종
    ( 크롬, 파폭, 오페라, 네이버내장브라우저, 페이스북내장브라우저 – 5종 +
    iOS5 에서 풀스크린이 지원되지 않는점, iOS7 에서 화면이 더 넓어진 점을 고려하면 사파리 3종 ) * 2(아이패드별도)
     
  • 안드로이드 공통 : 5종
    크롬, 파이어폭스, 돌핀, 오페라, 네이버내장브라우저 – 나머지는 점유율 상 무시
     
  • 갤럭시 내장 : 5종
    2, 2업뎃안함(꽤많음), 3, 4, 탭시리즈 전기종 – 나머지는 대략 이 넘들과 호환
     
  • 제조사별 최신 기종 : 7종
    엘지 G Gp G2 뷰 4종 + 베가 최근순으로 3종 – 나머지 HTC, 넥서스등 다 쌩깜.

이게 바로 최소 국내 스펙입니다. 비사이드는 일본 일을 하는데 그렇게 되면 위의 항목에 추가하여 기종별 내장 브라우저의 작동을 확인해야 하는데..

  • 구글 넥서스 시리즈 최근 순으로 : 3종
  • 소니는 OS별로 다 특이함. 진저, 아이스크림, 젤리빈 : 3종
  • 샤프, 도시바, 히타치 등 일본메이커 : 40여종..
  • 중국산 HTC, 하웨이, ZTE 등 중국 메이커 : 10여종..

이 추가됩니다.

예를 들어 소니의 이전 내장 브라우저 중 하나는 모두 손가락을 떼기 전에는 절대로 changedTouches 에 아무 것도 안들어오는 버그가 있습니다. 이것만으로도 위에 구축한 손가락별 이벤트는 개망입니다.

아이스크림 이후의 기종들은 제법 안정화 되었다고는 하나 모바일브라우저의 세계는 정말 즐겁게 해줍니다. =.=;

모쪼록 여러분의 건투를 빕니다.

 

 

=================================

=================================

=================================

 

 

 

출처: http://unabated.tistory.com/entry/Javascript-Touch-Gesture-Event-for-Mobile-Browser

 

 

Javascript Touch & Gesture Event for Mobile Browser

모바일/JAVAScript / jQuery 2011.03.08 13:04

 
모바일 브라우저의 Touch, Gesture Event 처리 방법에 대해서 정리해봅니다.
다른 여러 사이트에서 아이폰에대해서는 정리가 많이 되었던데요... 
저는 http://backtothecode.blogspot.com/2009/10/javascript-touch-and-gesture-events.html 이 블로그를 참조하여 아이폰과 안드로이드 폰에 대해서 함께 정리하여 봅니다.
 
 
Android and iPhone touch events
 
Android, iPhone은 공통적으로 터치와 관련해서 다음과 같은 이벤트를 제공합니다. 
  • touchstart - mouseDown 이벤트와 비슷한 이벤트로 손이 화면에 닿으면 발생
  • touchmove - mouseMove 이벤트와 비슷한 이벤트로 손 터치한 상태로 이동하면 발생
  • touchend - mouseUp 이벤트와 비슷한 이벤트로 손을 화면에서 뗄때 발생. 아이폰의 경우 touchcancel 이벤트가발생
  • touchcancel - bit of a mystery 라고 표현하네요. 쬐금 이상하다는...
 
예제)
document.addEventListener('touchstart', function(event) {
      alert(event.touches.length);
 }, false);

 
Event object
위의 예제에서 보듯이 Touch Event Object는 touches array를 포함하고 있다.
안드로이드의 경우 이벤트에는 한개의 터치 오브젝트를 포함한다. 즉 touches.length는 1이다.
터치 아이폰의 경우에는 멀티터치가 가능하기 때문에 touches array를 통해서 핸들링 할 수 있다. 
터치 이벤트 객체는 마우스 이벤트 객체와 같이 pageX, pageY 등의 값들을 포함하고 있다.
 
예제 )
document.addEventListener('touchmove', function(event) {
      event.preventDefault();
      var touch = event.touches[0];
      console.log("Touch x:" + touch.pageX + ", y:" + touch.pageY);
 }, false);

 
  • clientX: X coordinate of touch relative to the viewport (excludes scroll offset)
  • clientY: Y coordinate of touch relative to the viewport (excludes scroll offset)
  • screenX: Relative to the screen
  • screenY: Relative to the screen
  • pageX: Relative to the full page (includes scrolling)
  • pageY: Relative to the full page (includes scrolling)
  • target: Node the touch event originated from
  • identifier: An identifying number, unique to each touch event

 

iPhone Touch and Gesture Events

애플의 WebKit은 안드로이드와 달리 몇가지 것들을 추가적으로 지원한다. touchEnd 이벤트는 event.touches array에서 현재 touch 를 제거해준다. 대신 event.changeTouches array를 이용해서 볼 수 있다.
 
애플 iPhone의 터치 이벤트 객체
  • touches - touchStart, touchMove, touchEnd 의 터치 정보를 포함하고 있는 array
  • targetTouches - 같은 target Element로부터 비롯된 touches 정보를 포함
  • changedTouches - 모든 touch 정보를 가지고 있는 객체

 

Gesture events

애플에서는 pinching, rotating과 같은 멀티 터치 이벤트를 처리할 수 있도록 지원한다.
  • gesturestart - 멀티 터치 시작
  • gesturechange - 멀티 터치를 해서 움직일 때 발생
  • gestureend - 멀티 터치 이벤트가 끝날때 발생
멀티 터치를 위한 이벤트 객체는scale, rotation 값을 갖고 touch 객체가 없다.

예제 )
document.addEventListener('gesturechange', function(event) {
      event.preventDefault();
      console.log("Scale: " + event.scale + ", Rotation: " + event.rotation);
 }, false);

 
 

Event table

  touchstart touchmove touchend gesturestart gesturemove gestureend
Android y y y n n n
iPhone y y y y y y
has event.touches y y y n n n
(iPhone) has event.scale and event.rotation n n n y y y
(iPhone) touch in event.touches y y n - - -
(iPhone) touch in event.changedTouches y y y - - -
 
 
 
※ 참고 Link :
 
출처 - http://blog.hometown.co.kr/tag/touchmove



출처: http://unabated.tistory.com/entry/Javascript-Touch-Gesture-Event-for-Mobile-Browser [랄라라]

 

 

 

=================================

=================================

=================================

 

 

 

출처: http://skhugh.blogspot.kr/2014/08/blog-post.html

 

 

자바스크립트로 모바일웹 구현시 기본사항

 

Touch Event 추가하기

모바일에선 일반적으로 (안드로이드, ios 등) mouseDown, mouseMove, mouseUp 대신
touchstart, touchmove, touchend를 사용하면 된다.
단, 마소 IE의 경우 따로 MSPointerDown, MSPointerMove, MSPointerUP을 사용한다..

if (window.navigator.msPointerEnabled) {
element.addEventListener("MSPointerDown", eventHandlerName, false);
element.addEventListener("MSPointerMove", eventHandlerName, false);
element.addEventListener("MSPointerUp", eventHandlerName, false);
}
else {
element.addEventListener("touchstart", eventHandlerName, false);
element.addEventListener("touchmove", eventHandlerName, false);
element.addEventListener("touchend", eventHandlerName, false);
}

따라서 위와 같이 두 경우를 나눠줘야 함.



Multi Touch

멀티터치는 event의 touches 배열을 사용하면 된다.

document.addEventListener('touchmove', function(event) {
var touch1 = event.touches[0];
var touch2 = event.touches[1];
if(touch1 && touch2){
//멀티터치
}
else {
//싱글터치
}
}, false);
IE의 경우는 event.getPointerList(event.pointerID).length == 2 뭐 이런식으로 해야하는 듯.. 통일 좀 했으면 좋겟다.....



Click Delay

모바일 웹에서 클릭 이벤트를 구현해보면 클릭하고 약간의 지연시간(300ms)이 있다.
브라우저에서 다른 제스처들 (스와이프, 더블탭 등)을 확인하기 위해서인데 이게 의외로 답답하다. 이를 없애기 위해서 jquery mobile에서 tap 이벤트를 사용하거나 이와 관련해서 플러그인도 많으니 찾아 쓰면 된다.
직접 해결하려면 touchstart와 touchend를 사용해서 구현하면 된다.



preventDefault & stopPropagation

모바일에서 성능에 문제가 있을 때.. event.preventDefault()와 event.stopPropagation()을 적절히 사용하면 도움이 될 수 있다..

 

 

=================================

=================================

=================================

 

 

출처: https://ncube.net/10453

 

 

JavaScript를 이용해 좌우 swipe 방향 알아내기

JavaScript를 이용하여 터치기기에서 좌우 swipe 방향을 체크하는 개념적인 방법이다. 기본적인 아이디어 수준의 코드이기 때문에 실제 사용하는 것은 무리가 있을 것이라 생각한다. 사용자가 기기에 터치를 하면 touchstart 이벤트를 이용해 터치가 시작된 좌표를 기록해둔다. 그런 다음 touchend 이벤트를 이용해 터치가 끝났을 때 시작점의 좌표와 종료점의 좌표를 비교해서 swipe 방향을 체크하는 것이다. iOS 기기의 Safari 브라우저에서는 터치가 끝난 후 touchend 이벤트가 만료되지 않아 touches.length == 0 이라는 조건을 추가해서 체크하도록 했다. Android 기기에서는 바로 이벤트가 만료되는 듯 했다. 좌우로 swipe 하면서 완전히 일직선으로 움직이는 것은 불가능하기 때문에 약간의 허용오차를 둬서 오차범위일 때만 alert 함수가 실행된다.

얼핏보면 괜찮은 방법인 것 같은데 scroll 이벤트가 함께 발생하기 때문에 좌우 swipe 임에도 문서가 오르락내리락 할 수 있다. 이런 경우에도 대비를 해야하겠지만 당장은 방법이 떠오르지 않아 이정도에서 마무리를 한다. 이전에 포스팅했던 jQuery swipe 플러그인을 사용하면 scroll 이벤트까지 제어하면서 swipe 이벤트를 제대로 활용할 수 있다. 플러그인이 있는데 굳이 이런 걸 해본 것은 삽질을 좋아하기 때문이다. ㅋㅋ

 
 

 

 

=================================

=================================

=================================

 

 

 

출처: http://blog.iolo.kr/490

터치기반 모바일 웹킷에서 버튼 반응 속도 개선하기


아이폰/아이패드/아이팟의 모바일 사파리와 안드로이드의 모바일 크롬 등은 모두 터치기반 모바일 웹킷을 사용하는 브라우져들이다. 이 브라우져들은 버튼 등을 눌렀다(touchstart) 떼도(touchup) 즉시 반응(click)하지 않는데, 그 이유는 연속되는 터치 동작(touchstart-touchmove-touchend)들이 제스쳐(swipe, long click, …)인지 여부를 확인하기 위해 최대 300ms의 지연시간이 생기기 때문이다. 모바일 웹 사이트를 만드는 경우라면 이 정도의 지연시간은 크게 문제가 되지않지만, 상대적으로 신속한 반응을 요구하는 “웹앱"이라면 얘기가 달라진다.

해결책은 간단하다:
1. 손가락으로 무언가를 누르면(touchstart)
2. 웹킷의 기본 동작(300ms 지연)을 못하게 막고(preventDefault)
3. 움직임(touchmove) 없이
4. 손가락을 떼면(touchend)
5. 클릭(click)으로 간주한다.

touchstart/touchend을 mousedown/mouseup으로 바꿔놓고 보면 HTML5 이전에 drag & drop을 처리하기 위해서 사용하는 방식과 유사하다.

百聞不如一見! 코드를 살펴보자:

function NoClickDelay(el) {
this.element = el;
if( window.Touch ) this.element.addEventListener('touchstart', this, false);
}

NoClickDelay.prototype = {
handleEvent: function(e) {
switch(e.type) {
case 'touchstart': this.onTouchStart(e); break;
case 'touchmove': this.onTouchMove(e); break;
case 'touchend': this.onTouchEnd(e); break;
}
},

onTouchStart: function(e) {
e.preventDefault();
this.moved = false;

this.element.addEventListener('touchmove', this, false);
this.element.addEventListener('touchend', this, false);
},

onTouchMove: function(e) {
this.moved = true;
},

onTouchEnd: function(e) {
this.element.removeEventListener('touchmove', this, false);
this.element.removeEventListener('touchend', this, false);

if( !this.moved ) {
var theTarget = document.elementFromPoint(e.changedTouches[0].clientX, e.changedTouches[0].clientY);
if(theTarget.nodeType == 3) theTarget = theTarget.parentNode;

var theEvent = document.createEvent('MouseEvents');
theEvent.initEvent('click', true, true);
theTarget.dispatchEvent(theEvent);
}
}
};



百見不如一RUN! 코드를 돌려보자:

http://jsbin.com/exadi5



다시 말하지만, 위의 페이지는 터치기반의 모바일 웹킷, 즉 모바일 사파리나 모바일 크롬으로 봐야 효과가 있다.

일단 눈에 보이는 Slow Button과 Fast Button 각각을 평소대로 눌러보자. 클릭을 감지하는데 걸린 시간이 표시되는데, Fast 쪽이 조금 빠르긴 하지만 큰 차이는 없어 보인다.
이번에는 평소보다 좀 더 손끝에 감각을 모아서 “톡톡 두드린다는 느낌”으로 각 버튼을 눌러보자. Slow Button의 경우엔 아예 반응을 하지 않거나 확대(아이폰등에서는 더블탭이 자동 확대/축소)기능이 동작된다. Fast Button은 그런 동작을 하지 않는다.

이 글에서는 touchstart-touchmove-touchend 이벤트를 활용하여 버튼의 반응속도를 개선하는 방법을 알아보았다. 이 세가지 이벤트의 활용법을 잘 익혀두면 다양한 유형의 터치 입력을 처리하는데 많은 도움이 될 것이다.

참고 자료:
http://cubiq.org/remove-onclick-delay-on-webkit-for-iphone
http://code.google.com/mobile/articles/fast_buttons.html

 

 

 

 

=================================

=================================

=================================

 

 

 

터치이벤트를 지원하는 기기 태블릿 or 모바일의 경우 클릭 이벤트는 아래와같은 이벤트 순서로 진행된다.

 

touchstart - touchend - mouseover - mousemove - mousedown - mouseup - click

 

이 브라우져들은 버튼 등을 눌렀다(touchstart) 떼도(touchup) 즉시 반응(click)하지 않는다.

브라우저 자체적으로 연속되는 터치 동작(touchstart-touchmove-touchend)들이 제스쳐(swipe, long click, …)인지 여부를 확인하기 위해 최대 300ms의 지연시간이 생기기 때문. 

 

하지만 즉시반응하게 구현을 하려면 아래의 과정을 거치면 된다.

1. 손가락으로 무언가를 누르면(touchstart) 

2. 웹킷의 기본 동작(300ms 지연)을 못하게 막고(preventDefault)

3. 움직임(touchmove) 없이

4. 손가락을 떼면(touchend)

5. 클릭(click)으로 간주한다.

 

출처 : http://blog.iolo.kr/490

 



출처: http://dotweb.tistory.com/221 [절대로 고개를 떨구지 말라. 고개를 치켜들고 세상을 똑바로 바라보라.]

 

 

 

=================================

=================================

=================================

 

 

출처: http://sculove.github.io/blog/2016/12/29/addEventListener%EC%9D%98-%EC%9A%94%EC%83%81%ED%95%9C-%EC%98%B5%EC%85%98%EB%93%A4-%EC%A4%91%EC%9D%98-%ED%95%98%EB%82%98-passive/

 

 

Javascript Touch & Gesture Event for Mobile Browser

 

모바일 브라우저의 Touch, Gesture Event 처리 방법에 대해서 정리해봅니다.

다른 여러 사이트에서 아이폰에대해서는 정리가 많이 되었던데요... 
저는 http://backtothecode.blogspot.com/2009/10/javascript-touch-and-gesture-events.html 이 블로그를 참조하여 아이폰과 안드로이드 폰에 대해서 함께 정리하여 봅니다.
 
 
Android and iPhone touch events
 
Android, iPhone은 공통적으로 터치와 관련해서 다음과 같은 이벤트를 제공합니다. 
  • touchstart - mouseDown 이벤트와 비슷한 이벤트로 손이 화면에 닿으면 발생
  • touchmove - mouseMove 이벤트와 비슷한 이벤트로 손 터치한 상태로 이동하면 발생
  • touchend - mouseUp 이벤트와 비슷한 이벤트로 손을 화면에서 뗄때 발생. 아이폰의 경우 touchcancel 이벤트가발생
  • touchcancel - bit of a mystery 라고 표현하네요. 쬐금 이상하다는...
 
예제)
document.addEventListener('touchstart', function(event) {
      alert(event.touches.length);
 }, false);

 
Event object
위의 예제에서 보듯이 Touch Event Object는 touches array를 포함하고 있다.
안드로이드의 경우 이벤트에는 한개의 터치 오브젝트를 포함한다. 즉 touches.length는 1이다.
터치 아이폰의 경우에는 멀티터치가 가능하기 때문에 touches array를 통해서 핸들링 할 수 있다. 
터치 이벤트 객체는 마우스 이벤트 객체와 같이 pageX, pageY 등의 값들을 포함하고 있다.
 
예제 )
document.addEventListener('touchmove', function(event) {
      event.preventDefault();
      var touch = event.touches[0];
      console.log("Touch x:" + touch.pageX + ", y:" + touch.pageY);
 }, false);

 
  • clientX: X coordinate of touch relative to the viewport (excludes scroll offset)
  • clientY: Y coordinate of touch relative to the viewport (excludes scroll offset)
  • screenX: Relative to the screen
  • screenY: Relative to the screen
  • pageX: Relative to the full page (includes scrolling)
  • pageY: Relative to the full page (includes scrolling)
  • target: Node the touch event originated from
  • identifier: An identifying number, unique to each touch event

 

iPhone Touch and Gesture Events

애플의 WebKit은 안드로이드와 달리 몇가지 것들을 추가적으로 지원한다. touchEnd 이벤트는 event.touches array에서 현재 touch 를 제거해준다. 대신 event.changeTouches array를 이용해서 볼 수 있다.
 
애플 iPhone의 터치 이벤트 객체
  • touches - touchStart, touchMove, touchEnd 의 터치 정보를 포함하고 있는 array
  • targetTouches - 같은 target Element로부터 비롯된 touches 정보를 포함
  • changedTouches - 모든 touch 정보를 가지고 있는 객체

 

Gesture events

애플에서는 pinching, rotating과 같은 멀티 터치 이벤트를 처리할 수 있도록 지원한다.
  • gesturestart - 멀티 터치 시작
  • gesturechange - 멀티 터치를 해서 움직일 때 발생
  • gestureend - 멀티 터치 이벤트가 끝날때 발생
멀티 터치를 위한 이벤트 객체는scale, rotation 값을 갖고 touch 객체가 없다.

예제 )
document.addEventListener('gesturechange', function(event) {
      event.preventDefault();
      console.log("Scale: " + event.scale + ", Rotation: " + event.rotation);
 }, false);

 
 

Event table

  touchstart touchmove touchend gesturestart gesturemove gestureend
Android y y y n n n
iPhone y y y y y y
has event.touches y y y n n n
(iPhone) has event.scale and event.rotation n n n y y y
(iPhone) touch in event.touches y y n - - -
(iPhone) touch in event.changedTouches y y y - - -
 
 
 
※ 참고 Link :
 
출처 - http://blog.hometown.co.kr/tag/touchmove
 



출처: http://unabated.tistory.com/entry/Javascript-Touch-Gesture-Event-for-Mobile-Browser [랄라라]

 

 

 

=================================

=================================

=================================

 

 

 

출처: http://blim.co.kr/archives/6

 

 

모바일 swipe(플리킹) 기능 구현하기

들어가기 전에…
이 기능을 구현하기 위해서 먼저 두 가지를 생각해야 한다.

첫째, jquery animate로 구현할 것인지 혹은 css3의 animate기능을 구현할 것인지 선택해야 한다.
jquery animate로 결정하면, css3의 animate기능을 지원하지 않는 브라우저에서도 동일한 효과를 구현할 수 있다. 하지만 속도는 css3의 animate에 비해서 느리다.
반면에 css3의 animate로 결정하면, 속도가 빠르다. 만약 제작시에 클라이언트나 상사의 요구가 없다면 css의 animate로 구현할것을 권한다. 이 기능은 대부분의 모바일 브라우저에 사용할 것이고, 글을 쓰는 시점에서 브라우저중 css3의 animate를 지원하지 않는 것은 없었다.

두번쨰로 고려할것은, jquery를 사용할 경우이다. 만약 사용하는 jquery의 버젼이 1.9.1 이하이면 jquery의 버젼을 업그레이드 하거나 혹은 직접 css3 관련 함수를 구현하거나 cssHock기능을 사용해야 한다. 왜냐하면 jquery 1.9.1 이하버젼에서는 elemenet.css() 함수안에 css3 속성을 지원하지 않기 때문이다.

들어가기…
앞에서 두 가지를 결정하였다면, 이제 코드를 작성해야 한다.기본적으로는 롤링 배너에 터치 기능이 추가되기 때문에 관련 스크립트 소스가 있으면 더욱 좋을것 같다. 먼저 터치 관련 이벤트 함수를 알아야 한다. 모바일에 터치 기능이 추가되면서, 자연스럽게 javascript에도 이를 지원해주는 함수가 추가되었다. touchstart, touchmove, touchend이다. 이 세 이벤트는 이름 그대로이다. 다만 이들은 click함수와 이벤트 발생 순서만 차이 있을 뿐, 비슷하기 때문에 이를 구별해 주어야 한다.
각 이벤트별로 설명을 약간의 설명을 더하면,
먼저 터치 시작시 이벤트에는 시작 위치와 시작 이전의 원래위치를 기억해야만 한다.
터치중 이벤트에서는 기억된 시작위치에서 현재위치를 뺸 값을 css3 transition값에 대입하여 슬라이드 DOM이 따라오도록 해야 한다. 마지막으로 터치가 끝났을때는 사용자의 터치한 길이가 어느정도 이상이면 다음 슬라이드 혹은 이전 슬라이드로 이동하도록 하면 된다. 만약, 터치한 길이가 매우 짧으면 터치 시작시 기억한 시작 이전의 원래위치로 돌아가면 된다.
아래는 참고 소스이다.

var touch_start_y = 0; var touch_start_x = 0; var save_x = 0; var save_y = 0; var move_dx = 0;  element.addEventListener( 'touchstart', function( e ) {     if ( e.type === 'touchstart' && e.touches.length === 1 ) {         touch_start_x = e.touches[ 0 ].pageX;         touch_start_y = e.touches[ 0 ].pageY;     } }, false );  element.addEventListener( 'touchmove', function( e ) {     var drag_dist = 0;     var scroll_dist = 0;      if ( e.type === 'touchmove' && e.touches.length === 1 ) {         drag_dist = e.touches[ 0 ].pageX - touch_start_x;         scroll_dist = e.touches[ 0 ].pageY - touch_start_y;         move_dx = ( drag_dist / list_Width ) * 100;          if ( Math.abs( drag_dist ) > Math.abs( scroll_dist ) ) {              // ... move slide element              e.preventDefault( );         }     } }, false );  element.addEventListener( 'touchend', function( e ) {      if ( e.type === 'touchend' && e.touches.length === 0 ) {          if ( Math.abs( move_dx ) > 40 ) {             // ... move slide element to Next or Prev slide         } else {             // ... move slide element to save_x or save_y position         }          touch_start_y = 0;         touch_start_x = 0;         move_x = 0;         move_y = 0;         move_dx = 0;          e.preventDefault( );     } }, false ); 

추가 팁이 있다면, css3의 transition를 사용하게 될때 일부 디바이스에서는 번쩍거리는 현상이 있었다. 이런 현상이 있다면, 부모 DOM에 transform-style를 preserve-3d로 설정하여야 한다. 또한 일부 개발자중에 이벤트 전달 인자가 없거나 ie 브라우저를 생각하고 e = e || window.event 이런 코드를 삽입하는 경우가 있다. 이 코드를 삽입하게 되면 사용자가 터치 하지 않은 공간에서도 이벤트가 발생하니 유념하기 바란다.

정리하며…
앞에서도 언급했다시피, 롤링 배너위에 단순히 터치 기능만 추가된다고 생각하고 금방 하겠지 하고 들어갔지만 생각보다 고려할 상황이 많았다. 덕분에 모바일에 특성에 대해서 많이 배운 기회였던 것 같다.

 

 

 

=================================

=================================

=================================

 

 

*기타관련링크:

 

http://hacks.mozilla.or.kr/2016/11/control-mechanisms-in-javascript-games/

 

https://developers.google.com/web/fundamentals/design-and-ux/input/touch/?hl=ko

 

http://d2.naver.com/helloworld/80243

 

http://blog.hometown.co.kr/123

 

http://frontend.diffthink.kr/2016/05/click-touch.html

 

http://forgiveall.tistory.com/135

 

http://kwangheum.blogspot.kr/2014/05/html-click-300ms.html

 

http://fedev.tistory.com/29

 

 

 

=================================

=================================

=================================

 

 

 

 

 

 

반응형
그리드형


관련글 더보기

댓글 영역