繁体   English   中英

在AJAX调用“替换”跨度后,如何判断光标是否已经“动态”悬浮在动态跨度上?

[英]How can I tell if the cursor is *already* “hovered” over a dynamically placed span after an AJAX call “replaces” that span?

到目前为止,我已经将$(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();
});

然后,当您替换跨度中的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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM