javascript - 如何在 touchend 事件中获取 touchstart 值?

标签 javascript jquery ipad touch-event

我想在触发 touchend 事件时获取 touchstart.pageX 值,但我没有获得确切的值。它给了我 touchend 事件的 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

关于javascript - 如何在 touchend 事件中获取 touchstart 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8499735/

相关文章:

javascript - 非 ES6 Javascript 中如何处理类扩展?

iphone - 将 leftBarButtonItem 添加到导航栏时出现问题

ios - NSDate 在模拟器和设备(ipad)中不同

iphone - 将 xib 从一个项目复制到另一个项目

javascript - Angular 8 - 按数字过滤对象数组

javascript - 使用 JavaScript 打开 ModalPopupExtender

asp经典脚本 block 中使用的Javascript变量

JQuery:如何正确使用IF语句?

javascript - 使用对象在 html 中创建列表

jquery - jquery 中是否有迭代多个选择器的正确方法