从 iPhone 屏幕上的任意位置滚动 div
我想阻止 iPhone 上页面上的默认滚动操作(单个 div 除外)。基本上,当有人在屏幕上的任何位置滑动手指时,这个 div 应该移动。当有人直接触摸 div 元素时,我使用的代码工作正常,但否则 div 的位置相当不稳定。我哪里搞砸了?这是我在 Safari 开发者库。
<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) {
startY = curY;
}, false);
</script>
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) {
startY = curY;
}, false);
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
更改
curY
的值时,将-startY
更改为+startY
。问题不在于它仅在您触摸 div 时起作用。...pageY - touchY
的值将是自首次记录以来触摸移动的距离。如果之前的偏移量是 50 像素,并且向下移动了 20 像素,那么您希望新的偏移量为 20 + 50,而不是 20 − 50。您在第一次触摸时没有注意到问题,因为startY
接近于 0。事实上,startY
的初始值应该是 0,而不是 div 的offsetTop
,因为平移将是相对于起始偏移量应用。Change
- startY
to+ startY
when changing the value ofcurY
. 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 ofstartY
is close to 0. In fact, the initial value ofstartY
should be 0, and not theoffsetTop
of the div, since the translation will be applied relative to the starting offset.