2017-02-02 2 views
1

"요소"라는 이름의 개체가 있습니다. 누군가 타블렛에 닿으면 터치 위치의 x 및 y 좌표를 객체에 상대적으로 반환하고 싶습니다. 이자형. 객체의 왼쪽 위 모서리는 x = 0 및 y = 0 좌표를 갖습니다. 자바 스크립트가있는 태블릿의 터치 위치 결정

내가 데스크톱에서이를 구현하는 방법을 알고 :

$(function() { 
$(document).mousedown(function(e) { 
    var offset = $("#element").offset(); 
    var relativeX = (e.pageX - offset.left); 
    var relativeY = (e.pageY - offset.top); 
    alert(relativeX+':'+relativeY); 
    $(".position").val("afaf"); 
}); 
}); 

그래서 단어 "mousedown"가 "touchstart"로 대체해야한다, 그런 것 같아요. 그러나 여전히 작동하지 않습니다.

"mousedown"대신 "touchstart"가있는 태블릿에서 작동하도록 위 코드를 어떻게 변경합니까?

답변

1

touches 개체를 이벤트에서 명시 적으로 가져와야하며 좌표를 직접 포함하지 않아야합니다. 아래 코드의 두 번째 줄을보십시오. 여기

난 항상 터치를 얻기 위해 사용하는 코드입니다/포인터 좌표 :
if(e.type == 'touchstart' || e.type == 'touchmove' || e.type == 'touchend' || e.type == 'touchcancel'){ 
     var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0]; 
     x = touch.pageX; 
     y = touch.pageY; 
    } else if (e.type == 'mousedown' || e.type == 'mouseup' || e.type == 'mousemove' || e.type == 'mouseover'|| e.type=='mouseout' || e.type=='mouseenter' || e.type=='mouseleave') { 
     x = e.clientX; 
     y = e.clientY; 
    } 

는 이러한 이벤트의 일부 또는 전부를 수신 및 오프셋 계산을 추가하고이 일을해야 이벤트 리스너 내에서이 문제를 넣습니다.

+0

도움을 주셔서 감사합니다. 이제 완벽하게 작동합니다! – Tall83

+0

@ Tall83 당신을 환영합니다! – AllTheTime

0

일반적으로 예 : e.touches[0].clientX는 (다음 HTML

<div id="touchme" style="width: 200px; height: 200px; background: blue;"> 

그리고 스크립트 다음 스크립트는 첫 번째 처리

document.getElementById("touchme").addEventListener("touchstart", 
function clicked(e) { 
    var br = document.getElementById("touchme").getBoundingClientRect(); 
    // x & y are relative to the clicked element 
    var x = e.touches[0].clientX - br.left; 
    var y = e.touches[0].clientY - br.top; 
    console.log("x: " + x + " y: " + y); 
}); 

주를 가정 터치 이벤트

비 JQuery와 솔루션을 처리하기 위해 가능한 모든) 터치 입력

0

사용해보기 :

$(function(){ 

$('body').on('touchstart', function(e) { 
    var offset = $("#element").offset(); 
    var t = e.targetTouches.length > 0 ? e.targetTouches.item(0) : e.touches.item(0); 
    var relativeX = t.pageX - offset.left; 
    var relativeY = t.pageY - offset.top; 
    console.log(relativeX+':'+relativeY); 
    $(".position").val("afaf"); 
}); 

}); 
관련 문제