我正在倾听touchevents,当我使用pageX
/ pageY
调整layerX
/ layerY
值时,该点显示在圆圈的顶部我的触摸(我的手指),而不是中间。
//pageX = 310, layerX = -9. This is exactly in the middle of the touch circle horizontally
touchEvent.changedTouches[0].pageX + touchEvent.layerX
//pageY = 90, layerY = -34. This is exactly at the top of the touch circle!
touchEvent.changedTouches[0].pageX + touchEvent.layerX
当我检查触控圆的半径时,我看到的是半径为1:webkitRadiusX: 1
,webkitRadiusY: 1
(来自console.dir( touchEvent);
)。
我有三个问题:
为什么触摸屏幕时半径为“1”(Windows 8 / Chrome)会显示一个半径较大且“x”位于其中间的圆圈?
为什么我需要组合图层和页面坐标以获得与我单独使用mouseEVent图层坐标相同的值?
在touchEvent与mouseevent的元素中获取点的正确方法是什么?
代码
的index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Touch Test</title>
<script src="touch.js" type="text/javascript"></script>
</head>
<body>
<div id="touchBox" class="touchBox" style="position: relative; top: 19px; left: 0px; width: 638px; height: 142px; border: solid 1px #000000;"></div>
</body>
</html>
touch.js
window.Touch = {
init: function()
{
Touch.dom = document.getElementById( "touchBox" );
//Start listening
Touch.dom.addEventListener( "touchstart", Touch.mouseDown, false );
Touch.dom.addEventListener( "mousedown", Touch.mouseDown, false );
},
getPoint: function(touchEvent)
{
var x, y;
//Using touch events
if ( touchEvent.changedTouches && touchEvent.changedTouches[ 0 ] )
{
//Get the offset of the dom object
var offsety = Touch.dom.offsetTop || 0;
var offsetx = Touch.dom.offsetLeft || 0;
//The points within the dom object
x = touchEvent.changedTouches[0].pageX - offsetx + touchEvent.layerX;
y = touchEvent.changedTouches[0].pageY - offsety + touchEvent.layerY;
}
//Get points relative to the layer
else if ( touchEvent.layerX || 0 == touchEvent.layerX )
{
x = touchEvent.layerX;
y = touchEvent.layerY;
}
//Get the points relative to the dom object
else if ( touchEvent.offsetX || 0 == touchEvent.offsetX )
{
x = touchEvent.offsetX;
y = touchEvent.offsetY;
}
return { x: x, y: y };
},
mouseDown: function(mouseEvent)
{
//Make sure it doesn't move the page
mouseEvent.preventDefault();
mouseEvent.stopPropagation();
//Get the point
var point = Touch.getPoint( mouseEvent );
//Draw the point
var pointDiv = document.createElement( "div" );
pointDiv.style.width = "3px";
pointDiv.style.height = "3px";
pointDiv.style.backgroundColor = "#000000";
pointDiv.style.left = point.x + "px";
pointDiv.style.top = point.y + "px";
pointDiv.style.position = "absolute";
Touch.dom.appendChild( pointDiv );
//Print the point
console.dir( point );
}
};
window.addEventListener( "load", Touch.init );
答案 0 :(得分:1)
问题是抵消。这不是必需的。偏移量似乎已合并到layerX/Y
中。因此,将触摸事件的代码更改为:
//Using touch events
if ( touchEvent.changedTouches && touchEvent.changedTouches[ 0 ] )
{
//The points within the dom object
x = touchEvent.changedTouches[0].pageX + touchEvent.layerX;
y = touchEvent.changedTouches[0].pageY + touchEvent.layerY;
}