【问题标题】:Mouseover and Mouseout do not work when onload process is proceeded进行加载过程时,Mouseover 和 Mouseout 不起作用
【发布时间】:2019-08-21 06:10:12
【问题描述】:

我有一个 mouseover 事件和一个 mouseout 事件来显示和隐藏图像... 只要图像被完全缓存/加载,它就可以正常工作。

如果我在加载过程中快速浏览图像并离开特定的 div(鼠标悬停和 mouseout 应该触发的位置),则 mouseout 事件不会触发并且图像始终显示直到比(仅当我重新进入并离开时)缓存的图像它可以正常工作)。我猜想jquery卡在图像的onload过程中,无法识别mouseout事件。有什么解决办法吗?

$(document).on('mouseover',".divclass", { ....

loadImage(urllink);

function loadImage(src) {
    var image = new Image();
    image.onload = function() {
        if ('naturalHeight' in this) {
            if (this.naturalHeight + this.naturalWidth === 0) {
                this.onerror();
                return;
            }
        } else if (this.width + this.height == 0) {
            this.onerror();
            return;
        }
        // At this point, there's no error. Picture is available:
        $('#picture').attr('src', urllink);
        $(".image-content").stop().fadeIn(200);
    };
    image.onerror = function() {
        //display noimg.png
        $('#picture').attr('src', ".../noimg.png");
        $(".image-content").stop().fadeIn(200);

    };
    image.src = src;
}
...
});

 $(document).on('mouseout',".divclass", function (e) {
    $('.image-content').css("display", "none");
     });

使用 mouseenter/mouseleave 时会发生完全相同的错误。

【问题讨论】:

  • 你的容器div在图片加载之前有没有高度和宽度?
  • 它在一个 td 里面,它有 height:100%, display: flex;证明内容:中心;对齐项目:居中; ...在css中设置
  • 图片加载前div的渲染高度是多少?
  • 没有图像加载在“触发 div”之外的绝对位置......所以你将鼠标悬停在该 div 上并显示 img。因此,如果您在图像进出的加载过程(jquery 中的 onload)期间悬停鼠标悬停效果,则不会触发。也许我必须补充一点,图像不是由页面加载预加载的。它们是在悬停移动期间通过 jquery 动态加载的。
  • 这似乎是一个有趣的问题,可以从包含功能演示中受益。

标签: javascript jquery mouseover mouseout


【解决方案1】:

以防万一有人遇到同样的问题...

我无法消除错误,因为当图像的 .onload 正在进行时,jquery 似乎跳过了 mouseout/mouseleave 事件。此外,快速的鼠标移动会增加错误率。

我只是做了一个小解决方法:

   $(document).on('mousemove', function (e) {
     if ($(e.target).attr("class") !== "classname") { 
    $('.image-content').stop();
    $('.image-content').css("display", "none");
   e.stopPropagation();
     } else { return; }
     }); 

这样就行了……

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 2013-07-11
    • 2021-08-15
    • 2015-05-25
    相关资源
    最近更新 更多