最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Clone a DOM event object to re-dispatch - Stack Overflow

programmeradmin5浏览0评论

Some browsers won't allow you to re-dispatch an event that has already been dispatched, but allow you to create new event objects based on values that can be obtained from the existing event object.

Is there a generic and reusable solution that will work with any event type, or failing that, a way to do this for a specific event type (in my case I'm currently concerned with the mousewheel event)?

Some browsers won't allow you to re-dispatch an event that has already been dispatched, but allow you to create new event objects based on values that can be obtained from the existing event object.

Is there a generic and reusable solution that will work with any event type, or failing that, a way to do this for a specific event type (in my case I'm currently concerned with the mousewheel event)?

Share Improve this question edited Dec 18, 2019 at 11:20 vsync 130k59 gold badges340 silver badges421 bronze badges asked Oct 5, 2012 at 19:26 devios1devios1 38k48 gold badges167 silver badges267 bronze badges 1
  • 1 did you try element.dispatchEvent(your mousewheel event) ? You should be able to instanciate a new mousewheel event I think through createEvent(). – Sebas Commented Oct 5, 2012 at 19:39
Add a ment  | 

3 Answers 3

Reset to default 8

It seems there is now an even better solution, since initMouseEvent and the like are deprecated. The MouseEvent() constructor, for example, takes a table of properties as its second parameter, for which you can use an existing MouseEvent object:

let my_event = new MouseEvent(`foo`, some_existing_mouse_event);
dispatchEvent(my_event);

Other classes of events have similar constructors that should be usable in the same way. Such as ClipboardEvent().

jsfiddle example

I found my own answer, at least for MouseEvents specifically:

function cloneMouseEvent( e ) {
    var evt = document.createEvent( "MouseEvent" );
    evt.initMouseEvent( e.type, e.canBubble, e.cancelable, e.view, e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, e.button, e.relatedTarget );
    return evt;
}

You can then dispatch the event on a target with:

target.dispatchEvent( evt );

You may want to use the (poorly documented) NWEvents library

NW.Event.dispatch(target, e.type, false, e);

Works with any event, and in older IEs too.

发布评论

评论列表(0)

  1. 暂无评论