admin管理员组

文章数量:1400660

I've got the following code /

document.getElementById('obj_one').addEventListener('mouseover', function(){
    var e = document.createEvent('HTMLEvents');
    e.initEvent('mouseover', true, false);

    document.getElementById('obj_two').dispatchEvent(e);
    console.log('hover');
}, false);

I'm trying to make the #obj_two react to hover (thus changing to color red) when I mouseover on #obj_one, but it is not working. What am I doing wrong?

I've got the following code http://jsfiddle/yc7sj3pt/2/

document.getElementById('obj_one').addEventListener('mouseover', function(){
    var e = document.createEvent('HTMLEvents');
    e.initEvent('mouseover', true, false);

    document.getElementById('obj_two').dispatchEvent(e);
    console.log('hover');
}, false);

I'm trying to make the #obj_two react to hover (thus changing to color red) when I mouseover on #obj_one, but it is not working. What am I doing wrong?

Share Improve this question edited Sep 3, 2015 at 16:48 gespinha asked Sep 3, 2015 at 16:43 gespinhagespinha 8,50717 gold badges59 silver badges96 bronze badges 2
  • Why not add a class and do the styling that way instead? – James Brierley Commented Sep 3, 2015 at 16:48
  • @JamesBrierley I understand that solution, I wanted to do it too, but unfortunately I can't – gespinha Commented Sep 3, 2015 at 16:48
Add a ment  | 

1 Answer 1

Reset to default 5

According to this answer, you can't:

Events that are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the DocumentEvent.createEvent("Event") method, modified using the Event.initEvent() method, or dispatched via the EventTarget.dispatchEvent() method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false.

Most untrusted events should not trigger default actions, with the exception of click or DOMActivate events.

The remended approach instead is to add and remove a class on the mouseover and mouseout events, which I've done in this jsfiddle.

本文标签: javascriptdispatchEvent 39mouseover39 not workingStack Overflow