我有一个非常简单的代码,用于通过触摸屏拖动/移动元素。代码工作正常,唯一的问题是一个常见问题,但无论我如何尝试,我都无法修复从接触点拖动的代码。相反,无论初始触摸位置如何,每次移动都从元素的边缘开始。
我看到了一些建议,但都失败了。我希望更小更简单的代码会吸引一个简单的修复。
这是JavaScript:
<script>
$("#drag").on('touchmove',function(e){
// This is supposed to be the fix,
// but regardless of positioning
// (relative parent) of the divs,
// it is failing ---
var offset = $(this).offset();
var relX =(e.clientX - offset.left);
// By rights the above is the correct solution. But I
// cannot suss out why it is not working.
var touch = e.originalEvent.touches[0];
var x = touch.clientX
$(this).css({
"-webkit-transform": "translate3d("+ x +"px,"+ 0 +"px,0)"
});
});
</script>
<! --And here is the html -->
<body>
<div id="container" class="container">
<div id='drag' class='drag'>
<!---contents--->
</div>
</div>
CSS
#container {
position:relative;
top: 0%;
left: 0px;
width: 500px;
height: 500px;
background: #ccc;
}
#drag {
position:absolute;
top: 20%;
left: 10px;
width: 150px;
height: 10%;
background: #0a0;
}