到目前为止,我已经将$(document(.on事件用于mouseenter和mouseleave,它们的工作原理与他们所说的一样,也就是说,它们在进入和离开跨度时起作用。下面是该代码的片段:
$(document).on("mouseenter", ".hover_box", function() {
$(this).next('.hidden_iframe').prop("src", function(){
return $(this).data("src");
});
$(this).next('.hidden_iframe').show();
});
$(document).on("mouseleave", ".hover_box", function() {
$(this).next('.hidden_iframe').hide();
});
但是,当我的 AJAX 调用后跨度"重新加载"(.html替换(时,如果光标已经悬停在跨度上,它不会触发 mouseenter 事件(老实说,这真的并不让我感到惊讶(。
除了我可以使用 $(document(.on 来检测此状态之外,还有其他事件吗?或者我可以使用其他方法?
谢谢。
您可以设置一个全局变量来记住光标是否在该范围上,然后在重新加载后检查它。
var inSpan=false;
$(document).on("mouseenter", ".hover_box", function() {
inSpan=true;
$(this).next('.hidden_iframe').prop("src", function(){
return $(this).data("src");
});
$(this).next('.hidden_iframe').show();
});
$(document).on("mouseleave", ".hover_box", function() {
inSpan=false;
$(this).next('.hidden_iframe').hide();
});
然后,当您替换 span 中的 html 时,只需检查 inSpan 变量并采取相应的操作。
重新加载 HTML 后,您可以检查元素是否具有带有:hover
选择器的鼠标指针(无需为此保留全局变量(,如果是,则触发 mouseenter
事件:
if ($(".hover_box").is(":hover")) $(".hover_box").mouseenter();
一个简化的演示,当鼠标在span
元素上时,每 100 毫秒触发一次事件:
// For demo only, every 100ms trigger mouseenter if pointing to the span
setInterval(function () {
if ($(".hover_box").is(":hover")) $(".hover_box").mouseenter();
}, 100);
$(document).on("mouseenter", ".hover_box", function() {
console.log('mouseenter event triggered');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hover over span below to trigger mouseover every 100 ms: <br>
<span class="hover_box">[span]</span>