如何在touchend事件中获取touchstart值

how to get touchstart value in touchend event?

本文关键字:获取 touchstart 事件 touchend      更新时间:2023-09-26

我想接触一下。当触摸端事件被触发时,pageX值,但我没有得到确切的值。它给了我触摸端事件的pageX值。我做错了什么?

(function($){
    $.fn.extend({ 
        //pass the options variable to the function
        swipeTest: function(options) {
            var touchStart;            
            var options =  $.extend(defaults, options);
            //initilaized objects
            function init(thisObj){
                thisObj.addEventListener('touchstart', function(e) {
                    var touch = e.touches[0] || e.changedTouches[0];
                    touchStart = touch;
                    console.log('Value of touchStart.pageX in touchstart method: ' + touchStart.pageX);
                }, false);
                thisObj.addEventListener('touchend', function(e) {
                    var touch = e.touches[0] || e.changedTouches[0];
                    console.log('Value of touchStart.pageX in touchend method: ' + touchStart.pageX);
                }, false);
            }
            return this.each(function() {
                init(this);   
            });
        }
    });
})(jQuery);

在元素上滑动后,我在控制台得到这个(从左向右滑动)

Value of touchStart.pageX in touchstart method: 132
Value of touchStart.pageX in touchend method: 417
Value of touchStart.pageX in touchstart method: 32
Value of touchStart.pageX in touchend method: 481

为什么我在两种方法中都没有得到相同的值?我指向相同的变量!!

您应该在结束事件中获得touch变量的.target值。这就是触摸开始的地方。你甚至不需要touchStart变量。结束事件中的触摸包含了您需要的所有信息。

//in your touchend handler, after touch = blah blah blah
var startnode = touch.target; //gets you the starting node of the touch
var x = startnode.pageX
var y = startnode.pageY