【问题标题】:jQuery Trigger mouseenter on a element without actually real mouse entering elementjQuery在没有实际鼠标输入元素的元素上触发mouseenter
【发布时间】:2015-07-20 23:41:15
【问题描述】:

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

HTML

<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 秒。

我尝试过(分别):

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

没用。有没有办法做到这一点?

谢谢。

【问题讨论】:

  • 不确定我是否完全理解您的问题。但是在将您的代码放入 jsfiddle 之后,它似乎成功触发了 mouseover 和 mouseenter jsfiddle.net/p694huuk
  • 我不认为你做得对你的代码运行良好......你确定你的项目中有 jquery
  • 您在上面的代码中有拼写错误。 $("#hover_to_show_text").trigger("mouseenter"); 应该可以工作。
  • @epascarello 它不起作用。例如,当您将鼠标悬停在菜单中的“用户”上时,堆栈溢出将是橙色背景。但是,如果您将运行“$("#nav-users").trigger("mouseenter");"什么都不会发生。
  • 因为“用户”使用 CSS psudeo :hover 这不是 JavaScript 事件。你不会触发它。

标签: javascript jquery css mouseenter mouseleave


【解决方案1】:

应该可以。事件几乎立即触发。所以你可能没有看到区别。

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);

Check Fiddle

更新

// 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);

});

Update Fiddle

【讨论】:

  • @batz 第三个元素是什么意思。
  • 我的意思是另一个按钮例如会触发它。像这样:jsfiddle.net/Loof31rq/1
  • @batz 检查更新评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-20
  • 2013-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 2011-04-27
相关资源
最近更新 更多