我正在尝试使用触摸事件的pageX
值移动页面上的元素。我在下面的代码中放置了两个console.log
语句来跟踪pageX
值 - 第一个语句在touchstart
函数中输出pageX
值,第二个语句在手指在屏幕上移动时连续跟踪touchmove
函数中的pageX
值。
我希望touchmove
函数的pageX
值在我移动手指时不断变化,但它只是不断输出与touchstart
函数输出相同的内容。例如,如果touchstart
console.log
的输出256.55
pageX
值,那么touchmove
console.log
将连续输出值256.55
流,这就是我希望这个值发生变化的地方。
我尝试删除event.preventDefault();
语句,这只是对阻止pageX
更新的猜测?但这并没有改变任何事情。
pageX
值是否是跟踪连续 x 位置的正确值?
// event listener on an image that gets touched
lightboxImages[i].addEventListener('touchstart', touchMove);
function touchMove(event) {
console.log(touch.pageX);
event.preventDefault();
var touchedImage = event.target;
var touch = event.touches[0];
var moveOffsetX = touchedImage.offsetLeft - touch.pageX;
touchedImage.addEventListener('touchmove', function() {
console.log(touch.pageX);
var positionX = touch.pageX + moveOffsetX;
touchedImage.style.left = positionX + 'px';
}, false);
}
大部分代码取自: https://www.youtube.com/watch?v=_3b1rvuFCJY
编辑:我将代码重构为两个单独的函数,如下所示:
// event listeners on an image that gets touched
lightboxImages[i].addEventListener('touchstart', touchStart);
lightboxImages[i].addEventListener('touchmove', touchMove);
function touchStart(event) {
event.preventDefault();
touchedImage = event.target;
touch = event.touches[0];
moveOffsetX = touchedImage.offsetLeft - touch.pageX;
console.log(touch.pageX);
}
function touchMove(event) {
console.log(touch.pageX);
var positionX = touch.pageX + moveOffsetX;
//touchedImage.style.left = positionX + 'px';
touchedImage.style.left = touch.pageX + 'px';
}
..但仍然遇到同样的问题。
我发现将touchstart
的pageX
值分配给变量不会在touchmove
内更改,所以我不得不将touchmove
的event.touches[0]
分配给它自己的变量,如下所示:
function touchStart(event) {
event.preventDefault();
touchedImage = event.target;
touch = event.touches[0];
moveOffsetX = touchedImage.offsetLeft - touch.pageX;
}
function touchMove(event) {
// rather than trying to access variable touch from the touchstart function, I had to get event.touches[0] from touchmove's event
var movedTouch = event.touches[0];
var positionX = movedTouch.pageX + moveOffsetX;
touchedImage.style.left = positionX + 'px';
}