我有一个网页,其中的元素当鼠标悬停在元素上时,文本会出现在元素内。 我想生成“鼠标悬停”/“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');
没用。有办法做到吗?
谢谢。
最佳答案
应该可以。这些事件几乎立即被触发。所以您可能没有看到差异。
将 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
关于javascript - jQuery 在元素上触发 mouseenter,但实际上没有真正的鼠标输入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31528092/