在元素上触发mouseenter,而不是真正的鼠标进入元素

jQuery Trigger mouseenter on a element without actually real mouse entering element

本文关键字:元素 鼠标 mouseenter      更新时间:2023-09-26

我有一个网页的元素,当鼠标悬停在元素,文本出现在元素内。我想生成"鼠标悬停"/"mouseenter"来显示文本,即使没有鼠标实际悬停在元素上。代码示例:

<div> 
    <span id="hover_to_show_text">Hover here to show hidden text</span>
    <span id="hidden_text" style="display:none">Hidden text</span>
</div>    

JS

$( "#hover_to_show_text" ).mouseenter(function() {
   $( #hidden_text ).show();
});
 $( "#hover_to_show_text" ).mouseleave(function() {
   $( #hidden_text ).hide();
});

我想在jQuery中生成触发$("#hover_to_show_text").mouseenter(function(){"的"mouseenter",并让"mouseenter"停留N秒。

I tried (separate):

$("#hover_to_show_text").hover();
$("#hover_to_show_text").trigger('mouseover');
$("#hover_to_show_text").trigger('mouseenter');

不工作。有办法吗?

谢谢。

应该可以。这些事件几乎是立即触发的。所以你可能看不出有什么不同。

mouseleave的触发封装在setTimeout中以查看差异。

$( "#hover_to_show_text" ).mouseenter(function() {
   $('#hidden_text').show();
});
 $( "#hover_to_show_text" ).mouseleave(function() {
   $('#hidden_text').hide();
});
$("#hover_to_show_text").trigger('mouseover');
setTimeout(function() {
    $("#hover_to_show_text").trigger('mouseleave');
}, 1500);

检查小提琴

// Just triggering the click event will not work if no
// click handler is provided.
// So create one first
$("#btn").on('click', function () {
    // trigger the mouse enter event 
    $("#hover_to_show_text").trigger('mouseenter');
    setTimeout(function () {
        $("#hover_to_show_text").trigger('mouseleave');
    }, 1500);
});

更新小提琴