简体   繁体   English

Javascript,传递鼠标事件

[英]Javascript, passing on a mouse event

I would like a cross modern browser way to take a mouse event from one html element and pass it on to another. 我想用一种跨现代的浏览器方式从一个html元素中获取鼠标事件并将其传递给另一个。

eg. 例如。

el1.addEventListener('mousemove', function(e) {
  el2.trigger('mousemove', e);
});

el2.addEventListener('mousemove', function(e) {
   //THIS SHOULD BE CALLED WHEN EITHER el1
});

a jquery solution is ok but I would prefer a non-jquery solution. 一个jquery解决方案是可以的,但我更喜欢非jquery解决方案。 Is this simple? 这很简单吗?

Here is the correct code 这是正确的代码

var el1 = document.getElementById('el1');
var el2 = document.getElementById('el2');

el1.onmousemove = function(e) {
    alert('el1 event');
    el2.onmousemove(e);
};
el2.onmousemove = function(e) {    
    alert('el2 event');
};

demo 演示

This is good if you want the event argument e to pass over to el2 's event. 如果您希望事件参数e转移到el2的事件,这很好。 This updated demo shows mouse position being passed over. 此更新的演示显示鼠标位置被传递。

If you accept a jQuery answer then here's the code: 如果您接受jQuery答案,那么这里是代码:

// el1 and el2 are the jQuery objects of the DOM elements
el1.mousemove(function (event) {
    el2.mousemove(event);
});

In pure javascript: 在纯JavaScript中:

el1.onmousemove = function(e) {
    el2.onmousemove('mousemove', e);
};

el2.onmousemove = function(e) {

};
el1.addEventListener('mousemove', handler, false);
el2.addEventListener('mousemove', handler2, false);
function handler(e) {
    // do some stuff
    handler2.call(el2, e); // pass el2 as this reference, event as the argument.
};

not too sure if this is what you are looking for, just name the event handlers and trigger the one off the other. 不太确定这是否是您正在寻找的,只需命名事件处理程序并触发另一个。

if you do not need the this reference in the second handler, use handler2(e); 如果你不需要第二个处理程序中的this引用,请使用handler2(e); instead. 代替。

further readings: 进一步阅读:
Function.prototype.call Function.prototype.call

Here is a half-baked demo passing the mouse event args. 这是一个通过鼠标事件args 的半成品演示 I'm unsure how well supported layerX/Y is, I just used it to show the demo. 我不确定支持的layerX / Y有多好,我只是用它来展示演示。

native should work like that 本地人应该这样工作

var evt;
el1.onmousemove = function() {
  evt = document.createEvent('MouseEvent');
  evt.initEvent('mousemove', true, true);
  el2.dispatchEvent(evt);
}

You can read up on element.dispatchEvent here: 你可以在这里阅读element.dispatchEvent
https://developer.mozilla.org/en-US/docs/DOM/element.dispatchEvent https://developer.mozilla.org/en-US/docs/DOM/element.dispatchEvent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM