如何在我的手指已经在屏幕上之后添加到DOM的元素上捕获touchmove事件? [英] How can I catch touchmove events on an element that is added to the DOM after my finger is already on the screen?

查看:166
本文介绍了如何在我的手指已经在屏幕上之后添加到DOM的元素上捕获touchmove事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为iPad开发一个javascript / html5项目。

I am working on a javascript / html5 project for iPad.

我需要能够捕获一个未添加到<的元素上的touchmove事件code> DOM 直到 touchstart 事件被触发后(即在一个人将手指放在屏幕上之后)。

I need to be able to catch touchmove events on an element that does not get added to the DOM until after a touchstart event has fired (ie until after a person has put their finger on the screen.)

我试过模拟一个 touchstart 事件并以编程方式触发它...

I have tried simulating a touchstart event and firing it programatically...

$( "#container" ).append( element );
element.on( "touchmove", doStuff );
var ev = $.Event( "touchstart" );
element.trigger( ev );

...但这不起作用。我可以获得 doStuff 开始射击的唯一方法是抬起我的手指,然后再次触摸屏幕,触发第二个 touchstart event。

...however this does not work. The only way I can get doStuff to start firing is to lift my finger and then touch the screen again, triggering a second touchstart event.

如何在添加到<$ c $的元素上捕获 touchmove 事件c> DOM 我的手指已经在屏幕上?

How can I catch touchmove events on an element that is added to the DOM after my finger is already on the screen?

推荐答案

总结一下,你似乎想要:

To summarise, you appear to want :


  • 在touchstart上:显示和定位样式化div元素。

  • on touchmove:拖动元素而不释放并重新按下鼠标按钮

  • on touchstart: to display and position a styled div element.
  • on touchmove: to drag the element without releasing and re-pressing the mouse button.

如果这种解释是正确的,然后答案是处理最初点击的相同元素上的touchmove事件 - 即body元素。没有必要处理要拖动的元素的touchmove事件(添加的元素)。

If this interpretation is correct, then the answer is to to handle touchmove events on the same element that was originally clicked on - namely the "body" element. It is not necessary to handle touchmove events of the element you want to drag (the added element).

必须有很多方法来编写代码。这是一个,这可能不是你想要的(主要是在定位数学中),但应该很容易适应:

There must be many ways to write the code. Here's one, which is probably not exactly what you want (chiefly in the positioning maths) but should be simple to adapt :

var $element = $("<div class='element' />");

$("body").on({
    'touchstart mousedown': function (e) {
        $element.appendTo("body");
        $(this).on('touchmove mousemove', move);
        move(e);//you could do `$(this).trigger('touchmove', e)` but a conventional function call keeps `move` simple.
    },
    'touchend mouseup': function (e) {
        $(this).off('touchmove mousemove');
    }
});

function move(e) {
    $element.css({
        left: (e.pageX - 10) + 'px',
        top: (e.pageY - 10) + 'px',
        cursor: 'pointer'
    });
}

mousedown / mousemove / mouseup允许进行桌面测试,可以删除用于触摸设备。

DEMO

DEMO

这篇关于如何在我的手指已经在屏幕上之后添加到DOM的元素上捕获touchmove事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆