I'd like to prevent the default scrolling action on my page on an iPhone with the exception of a single div. Basically, when someone swipes their finger across the screen--anywhere on the screen--this single div ought to move. The code I'm using works fine when someone is directly touching the div element, but otherwise the position of the div is pretty erratic. Where am I messing up? This is a loose modification of what I found in the Safari Developer Library.
<div id="testdiv">
test test test test
</div>
<script type="text/javascript">
var startY = document.getElementById("testdiv").offsetTop;
var curY = startY;
var touchY;
document.addEventListener('touchstart', function(event) {
touchY = event.targetTouches[0].pageY;
}, false);
document.addEventListener('touchmove',function(event) {
event.preventDefault();
curY = event.targetTouches[0].pageY - startY - touchY;
document.getElementById("testdiv").style.webkitTransform = 'translate(0px,' + curY + 'px)';
}, false);
document.addEventListener('touchend',function(event) {
sta开发者_运维技巧rtY = curY;
}, false);
</script>
Change - startY
to + startY
when changing the value of curY
. The problem was not that it only worked when you touched the div. The value of ...pageY - touchY
will be the distance the touch has moved since it was first recorded. If the previous offset was 50 pixels and it was moved 20 pixels down, then you want the new offset to be 20 + 50, not 20 − 50. You didn't notice the problem on the first touch because the initial value of startY
is close to 0. In fact, the initial value of startY
should be 0, and not the offsetTop
of the div, since the translation will be applied relative to the starting offset.
精彩评论