从 iframe 调用父级的触摸事件

Call touch event on parent from iframe

我正在尝试在用户与 iframe 交互时调用触摸移动事件。

此代码位于包含 iframe 的顶级页面。

var myIframe = document.getElementById('iFrame');
var myIframeDoc = myIframe.contentWindow.document;
myIframeDoc.addEventListener('touchmove', function(event){

    console.log('iframe touched');

    var e = document.createEvent('TouchEvent');
    //e.touches = [{pageX: 10, pageY: 10}];
    //e.initTouchEvent('touchstart', true, true);
    e.initUIEvent('touchstart', true, true);

}, false);

所以当用户触摸在 iframe 上移动时,它将调用下面的事件之一(也在顶级页面)。

document.addEventListener("touchmove", function(event){

    alert('touchmove');

});

document.addEventListener("touchstart", function(event){

    alert('touchstart');

});

document.addEventListener("touchend", function(event){

    alert('touchend');

});

但是触摸事件不会在父层上触发...但是控制台日志工作正常,所以它正在获取 iframe touchmove,但 TouchEvent 部分似乎没有工作。

简而言之,我需要能够触发事件,就像用户在与 iframe 交互时触摸了父页面一样。

您没有调度事件。我还必须将其创建为 MouseEvent.

document.addEventListener("touchstart", function (event) {
    alert('touchstart');
});
// Fix 1 (test in mobile, it may need to be feature detected)
// Or not work reliably across browsers, some clients will need TouchEvent
var e = document.createEvent('MouseEvent');
e.initUIEvent('touchstart', true, true);
//Fix 2
document.dispatchEvent(e);