在 JavaScript 中以编程方式触发 onmouseover 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2228376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:21:10  来源:igfitidea点击:

Trigger onmouseover event programmatically in JavaScript

javascriptdom-eventsonmouseover

提问by fearofawhackplanet

Is there a way to programmatically trigger the onmouseoverevent in plain JavaScript? or "extract" the method from the onmouseoverevent to call it directly?

有没有办法onmouseover在纯 JavaScript 中以编程方式触发事件?或从onmouseover事件中“提取”方法以直接调用它?

eg

例如

<div id="bottom-div" onmouseover="myFunction('some param specific to bottom-div');">
    <div id="top-div" onmouseover="????????"></div>
</div>

top-div is above bottom-div, so the onmouseoverwon't get fired in bottom-div. i need a way of calling myFunction('some param specific to bottom-div');from top-div

顶部 div 高于底部 div,因此onmouseover不会在底部 div 中被触发。我需要一种myFunction('some param specific to bottom-div');从 top-div调用的方法

采纳答案by Yacoby

You would do it something like this:

你会这样做:

document.getElementById('top-div').onmouseover();

However, as mentioned in the comments, it would be worth testing before being considered an issue.

但是,正如评论中提到的,在被视为问题之前值得测试。

回答by Jonathan

This worked for me in IE9 at least. Should be cross-browser compatible or close to it...

这至少在 IE9 中对我有用。应该跨浏览器兼容或接近它...

function FireEvent( ElementId, EventName )
{
    if( document.getElementById(ElementId) != null )    
    {   
        if( document.getElementById( ElementId ).fireEvent ) 
        {
            document.getElementById( ElementId ).fireEvent( 'on' + EventName );     
        }
        else 
        {   
            var evObj = document.createEvent( 'Events' );
            evObj.initEvent( EventName, true, false );
            document.getElementById( ElementId ).dispatchEvent( evObj );
        }
    }
}

For onmouseover example, call the function like this

对于 onmouseover 示例,像这样调用函数

FireEvent( ElementId, "mouseover" );

回答by givehug

const mouseoverEvent = new Event('mouseover');

whateverElement.dispatchEvent(mouseoverEvent);

回答by Jonathan

I had to revise my RefreshMouseEvents set of functions after more testing. Here is the seemingly perfected version (again only IE9 tested):

经过更多测试后,我不得不修改我的 RefreshMouseEvents 函数集。这是看似完美的版本(再次仅经过 IE9 测试):

function RefreshMouseEvents( ElementId ) 
{
    FireEvent( ElementId, 'mouseover' );
    setTimeout( "TriggerMouseEvent( '" + ElementId + "', '" + event.clientX + "', '" + event.clientY + "' )", 1 );
}

function TriggerMouseEvent( ElementId, MouseXPos, MouseYPos )
{
    if( IsMouseOver( ElementId, (1*MouseXPos), (1*MouseYPos) ) )
        FireEvent( ElementId, 'mouseover' );
    else    
        FireEvent( ElementId, 'mouseout' );
}

function IsMouseOver( ElementId, MouseXPos, MouseYPos )
{
    if( document.getElementById(ElementId) != null )    
    {
        var Element = document.getElementById(ElementId);   
        var Left  = Element.getBoundingClientRect().left, 
            Top   = Element.getBoundingClientRect().top,
            Right = Element.getBoundingClientRect().right,
            Bottom  = Element.getBoundingClientRect().bottom;       
        return ( (MouseXPos >= Left) && (MouseXPos <= Right) && (MouseYPos >= Top) && (MouseYPos <= Bottom))    
    }
    else
        return false;
}

function FireEvent( ElementId, EventName )
{
    if( document.getElementById(ElementId) != null )    
    {   
        if( document.getElementById( ElementId ).fireEvent ) 
        {
            document.getElementById( ElementId ).fireEvent( 'on' + EventName );     
        }
        else 
        {   
            var evObj = document.createEvent( 'Events' );
            evObj.initEvent( EventName, true, false );
            document.getElementById( ElementId ).dispatchEvent( evObj );
        }
    }
}

回答by Kishan

For me following worked:

对我来说,以下工作:

?document.getElementById('xyz').dispatchEvent(new MouseEvent('mouseover', { 'bubbles': true }));

Also:

还:

?document.getElementById('xyz').dispatchEvent(new MouseEvent('mouseover', { 'view': window, 'bubbles': true, 'cancelable': true }));

回答by Jonathan

Without going into too much detail, I had an img with rollovers, i.e. mouseout/overs that set the img src to hidden form values (or this could have done in a different context with gloabl variables). I used some javascript to swap both of my over/out image values and I called the called FireEvent( ElementId, "mouseover" ); to trigger the change. My javascript was hiding / displaying elements on the page. This caused the cursor to sometimes be over the img I used to trigger the event - which was the same as the one I was swapping out, and sometimes the cursor was not over the img after the click.

没有详细说明,我有一个带有翻转的 img,即鼠标移出/悬停将 img src 设置为隐藏的表单值(或者这可以在具有 global 变量的不同上下文中完成)。我使用了一些 javascript 来交换我的两个过/出图像值,并调用了名为 FireEvent( ElementId, "mouseover" ); 来触发变化。我的 javascript 在页面上隐藏/显示元素。这导致光标有时会在我用来触发事件的 img 上方 - 这与我换出的那个相同,有时在单击后光标不在 img 上方。

Mouseover/out does not fire unless you exit and re-enter an element, so after my event was triggered the mouseover/out needed "retriggering" to account for the new cursor position. Here is my solution. After I hide / display various page elements, and to do my img src swapping as described, I call the function RefreshMouseEvents( ElementId ) instead of FireEvent( ElementId, "mouseover" ).

除非您退出并重新输入元素,否则鼠标悬停/移出不会触发,因此在触发我的事件后,鼠标悬停/移出需要“重新触发”以说明新的光标位置。这是我的解决方案。在我隐藏/显示各种页面元素并按照描述进行 img src 交换之后,我调用函数 RefreshMouseEvents( ElementId ) 而不是 FireEvent( ElementId, "mouseover" )。

This works in IE9 (not sure about other browsers).

这适用于 IE9(不确定其他浏览器)。

function RefreshMouseEvents( ElementId )
{
    FireEvent( ElementId, 'mouseover' );
    setTimeout( "TriggerMouseEvent( '" + ElementId + "' )" , 1 );
}

function TriggerMouseEvent( ElementId )
{
    if( IsMouseOver( ElementId, event.clientX, event.clientY ) )
        FireEvent( ElementId, 'mouseover' );
    else    
        FireEvent( ElementId, 'mouseout' );
}

function IsMouseOver( ElementId, MouseXPos, MouseYPos )
{
    if( document.getElementById(ElementId) != null )    
    {
        var Element = document.getElementById(ElementId);   
        var Left  = Element.getBoundingClientRect().left, 
            Top   = Element.getBoundingClientRect().top,
            Right = Element.getBoundingClientRect().right,
            Bottom  = Element.getBoundingClientRect().bottom;       
        return ( (MouseXPos >= Left) && (MouseXPos <= Right) && (MouseYPos >= Top) && (MouseYPos <= Bottom))    
    }
    else
        return false;
}

function FireEvent( ElementId, EventName )
{
    if( document.getElementById(ElementId) != null )    
    {   
        if( document.getElementById( ElementId ).fireEvent ) 
        {
            document.getElementById( ElementId ).fireEvent( 'on' + EventName );     
        }
        else 
        {   
            var evObj = document.createEvent( 'Events' );
            evObj.initEvent( EventName, true, false );
            document.getElementById( ElementId ).dispatchEvent( evObj );
        }
    }
}

回答by thephatp

I needed to do something similar, but I'm using jQuery, and I found this to be a better solution:

我需要做类似的事情,但我使用的是 jQuery,我发现这是一个更好的解决方案:

Use jQuery's trigger function.

使用jQuery的触发功能。

$j('#top-div' ).trigger( 'mouseenter' );

You can also add parameters to it if you need to. See the jQuery documentation on .trigger.

如果需要,您还可以向其添加参数。请参阅.trigger 上jQuery 文档

回答by Reigel

?<a href="index.html" onmouseover="javascript:alert(0);" id="help"?????????????????????????????????????????????????????????????>help</a>???????????????????????????

?document.getElementById('help').onmouseover();???????