将鼠标事件调度到iframe窗口?

时间:2014-03-26 14:13:38

标签: javascript html iframe

我有两个兄弟div(绝对定位)。

    ________________
    |              |
    |  BACK DIV    |
    |     _________|_____
    |     |             |
    |     |  FRONT DIV  |
    |_____|             |
          |             |
          |_____________| 

经过一番努力,我设法将事件从一个div调度到另一个div。

var backDiv = document.getElementById('back');
var frontDiv = document.getElementById('front');
var logger = document.getElementById('logger');

backDiv.addEventListener('mousedown', function(e) {
    logger.innerHTML += 'back<br />';
});

frontDiv.addEventListener('mousedown',function(e) {
    logger.innerHTML += 'front<br />';

    var e1 = document.createEvent('MouseEvent');
    e1.initMouseEvent(e.type, e.bubbles, e.cancelable, e.view, e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, e.button, null);

    console.log(backDiv.contentWindow)
    backDiv.contentWindow.document.body.dispatchEvent(e1);
}, true);

var backDiv = document.getElementById('back'); var frontDiv = document.getElementById('front'); var logger = document.getElementById('logger'); backDiv.addEventListener('mousedown', function(e) { logger.innerHTML += 'back<br />'; }); frontDiv.addEventListener('mousedown',function(e) { logger.innerHTML += 'front<br />'; var e1 = document.createEvent('MouseEvent'); e1.initMouseEvent(e.type, e.bubbles, e.cancelable, e.view, e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, e.button, null); console.log(backDiv.contentWindow) backDiv.contentWindow.document.body.dispatchEvent(e1); }, true); 这是code

我在后面放置一个iframe,在前面放置div,

    ________________
    |              |
    | BACK IFRAME  |
    |     _________|_____
    |     |             |
    |     |  FRONT DIV  |
    |_____|             |
          |             |
          |_____________| 

我想将前端div中的鼠标事件发送到iframe。 我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

尝试将父元素(比如#container)添加到iframe,然后:

section

并记住要听取父文件中触发的事件

var event = document.createEvent('Event');
event.initEvent('CustomEvent', true, true);
event.targetFrame = "myTargetFrame";
element = parent.document.getElementById('container');
element.dispatchEvent(event);

并且因为您检查了目标框架,所以在多个框架触发的事件中不会发生任何冲突