我有一个非常简单的代码,用于通过触摸屏拖动/移动元素。代码工作正常,唯一的问题是常见的问题,但无论我如何尝试,我无法修复从接触点拖动的代码。相反,无论初始触摸位置如何,每个动作都从元素的边缘开始。
我看到了一些建议,但都失败了。我希望更小的简单代码能够吸引简单的修复。
这是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;
}
答案 0 :(得分:0)
这是答案,重新编写并从别处获得一些帮助。
但对于其他任何一天在同一位置并来到这里寻求建议的人,你会在这里找到它:
.container{
position:absolute;
top:0%;
left:0%;
width:500px;
height:100%;
}
.drag{
position:absolute;
top:1%;
left:1%;
width:100%;
height:15%;
border-style: solid; 1px;
border-color: blue;
z-index:1000;
}
HTML
<div id="container" class="container">
<div id='drag' class='drag'>
<center> ...content drag me... </center>
</div>
</div>
的JavaScript。
<script>
document.querySelector(".container").addEventListener("touchmove", function(event) {
event.preventDefault(); // Prevent scrolling of window while touchevent triggerd for element.
});
window.addEventListener('load', function(){
var box = document.getElementById('drag'), // the element or box
bleft=0 , // left position of moving element/box
sx=150, // starting x touch point - half the element width is best.
ds = 0, // distance traveled by touch point
tob = null // Touch object holder
box.addEventListener('touchmove', function(e){
var box = document.getElementById('drag'),
tob = e.changedTouches[0] // reference first touch point for this event
var ds = parseInt(tob.clientX) - sx // calculate dist traveled by touch point
box.style.left = ( (bleft + ds > 400)? 400 : (bleft + ds < -10000000)? -10000000 : bleft + ds ) + 'px' // distance element can travel in X direction
box.addEventListener('touchstart', function(e){
var box = document.getElementById('drag'),
tob = e.changedTouches[0] // reference first touch point
bleft = parseInt(box.style.left) // get left position of box
sx = parseInt(tob.clientX) // get x coord of touch point
}, false) // return null activity or event if none
}, false)
}, false)
</script>