javascript - 鼠标悬停在 jquery 上更改图片时的延迟

标签 javascript jquery html

我需要在鼠标悬停时更改图片,我尝试了两种不同的方法 但它们似乎滞后,或者有时不起作用,或者有时起作用取决于我检查它的那一刻。 我使用的jquery库:http://code.jquery.com/jquery-1.9.1.js 也许问题出在我使用的库上(我不知道)。 对于示例的具体 html:

<img id="imgrotate" src="http://pursuitnotes.com/wp-content/uploads/2012/07/Einstein-Funny-Face.jpg" width="350" height="350" alt="Einstein-Funny-Face">

以及 2 个不同的 js 代码:

$(document).ready(function() {
    $("img").on({
        "mouseover": function() {
            this.src = "http://www.dorkbotswiss.org/wp-					  content/uploads/2014/08/funnny-2.jpg";
        },
        "mouseout": function() {
            this.src = "http://pursuitnotes.com/wp-  content/uploads/2012/07/Einstein-Funny-Face.jpg";
        }
    });
});

第二个:

$(document).ready(function() {
    $("img").on({
        "mouseenter": function() {
            this.src = "http://www.dorkbotswiss.org/wp-content/uploads/2014/08/funnny-2.jpg";
        },
        "mouseleave": function() {
            this.src = "http://pursuitnotes.com/wp-content/uploads/2012/07/Einstein-Funny-Face.jpg";
        }
    });
});

第二个只是 mouserover - mouseenter 和 mouseout-mouseleave 之间的细微差别。

所以我的问题是为什么会延迟,以及为什么它不能一直完美工作。有时我什至需要点击图片才能触发它工作。

这是 2 个 fiddle : http://jsfiddle.net/pxx71p8c/13/ http://jsfiddle.net/pxx71p8c/4/

提前致谢。

最佳答案

您正在更改图像标签的来源,这将使 dom 再次加载图像。它可能会缓存到浏览器临时文件中,但 dom 仍然需要再次加载它。

解决方案 - 更好地创建多个 <img>具有不同来源的标签并相应地显示/隐藏它们。

<div id ="image">
    <img 1>
    <img 2>
</div>

更好的选择是将鼠标事件放在容器 div 上。

关于javascript - 鼠标悬停在 jquery 上更改图片时的延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34293171/

相关文章:

javascript - 使用 Async/Await 获取 API 'POST' 的正确方法

JavaScript 变量似乎被视为函数

jQuery 到 MooTools

javascript - 删除 url 中的最后一个元素

javascript - 如何通过点击按钮实现背景图片位置变化的幻灯片效果

javascript - 限制悬停时 jquery 执行(次/次)

javascript - 语法错误 : ES6 Switch case inside If else ternary Operator

Jquery UI 可拖动/可排序,无需按住鼠标按钮

html - 如何用 "shared border"创建多个 div?

javascript - Intro.js 指南编号略有移位