页面 X 值未在触摸移动功能中更新



我正在尝试使用触摸事件的pageX值移动页面上的元素。我在下面的代码中放置了两个console.log语句来跟踪pageX值 - 第一个语句在touchstart函数中输出pageX值,第二个语句在手指在屏幕上移动时连续跟踪touchmove函数中的pageX值。

我希望touchmove函数的pageX值在我移动手指时不断变化,但它只是不断输出与touchstart函数输出相同的内容。例如,如果touchstartconsole.log的输出256.55pageX值,那么touchmoveconsole.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';
}

..但仍然遇到同样的问题。

我发现将touchstartpageX值分配给变量不会在touchmove内更改,所以我不得不将touchmoveevent.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';
}

最新更新