【问题标题】:jQuery how to prevent mouseenter triggering when page loads with cursor hovering elementjQuery如何在使用光标悬停元素加载页面时防止mouseenter触发
【发布时间】:2011-09-26 09:59:17
【问题描述】:

我的页面上有一个元素,它绑定了一个 mouseenter 事件,它改变了子图像的尺寸。

它可以按我的意愿工作,但是如果您将光标悬停在 div 所在的位置点击页面,它会在加载后立即触发 - 这是不希望的,我希望它在鼠标光标实际出现之前什么都不做 进入 div,而不是从那里开始。

我尝试在 jsfiddle 上敲出一个示例,但页面加载速度太快,我无法将光标放在正确的位置 :(

一种可能性是将绑定方法调用置于超时状态,以便绑定事件需要一秒钟,但如果用户将光标悬停在我的 div 上,问题仍然会发生。

有什么想法吗?

使用 jQuery 1.6.2

【问题讨论】:

  • 把你的函数包裹在 window.onload = function() {...} 可以解决这个问题。
  • @ScottSimpson 现在已经有一段时间了,我意识到我没有提供示例代码,但是代码被包裹在 jQuery(function(){}); 中,它做同样的事情。
  • 不是 jQuery(function(){}); document.ready 的快捷方式? window.onload 在所有资产加载后触发,document.ready 在文档准备好后触发。这可以产生影响,对我来说也是如此——尤其是在 Firefox 中。
  • @ScottSimpson 是的,你是对的,抱歉这些天我对 jQuery 有点生疏了!

标签: jquery mouseenter


【解决方案1】:

嗯。这是唯一的想法。

var mouse_already_there = false;
var event_set = false;
$(document).ready(function() {
    $(item).hover(function(){
        if(!event_set) { mouse_already_there = true; }
    }, function(){
        if(!event_set) { mouse_already_there = false; }
    });
    if(mouse_already_there) {
        //do nothing
    } else {
        event_set = true;
        //set event
    }
});

【讨论】:

  • 哇!应该想到这一点:)
【解决方案2】:

我的工作解决方案是:

    var mouseenterno = 0;

    $('.selector').on('mouseenter', function() {

       //your code here

        mouseenterno = mouseenterno + 1;

    });

    $('.selector').on('mouseleave', function() {

        if (mouseenterno >= 1){

           //your code here

        }

    });

【讨论】:

    猜你喜欢
    • 2011-02-23
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2021-05-23
    • 2011-09-24
    相关资源
    最近更新 更多