[英]How to avoid a new request when changing an image in a hover event?
I'm trying to create an event with jQuery that changes an image when the user hovers over it. 我正在尝试使用jQuery创建一个事件,当用户将鼠标悬停在该事件上时会更改图像。 The problem I have is that even though I have preloaded the image using jQuery, when the user hovers over the image, it makes a new request and loads the image again (it is already showed in the developers console as a preloaded image since the page was first loaded).
我遇到的问题是,即使我已经使用jQuery预加载了图像,当用户将鼠标悬停在图像上时,它也会发出一个新请求并再次加载该图像(自页面以来,它已在开发人员控制台中显示为预加载的图像。首次加载)。 I guess there is something wrong with the way I'm changing the CSS property with jQuery, but I can't find the right way to do it anywhere.
我猜我用jQuery更改CSS属性的方式出了点问题,但是我找不到在任何地方做的正确方法。
Here's the code: 这是代码:
HTML: HTML:
<div id="box" class="box">
</div>
CSS: CSS:
.box
{
height: 100px;
width: 500px;
border-radius: 15px;
background-color: #003366;
background-image: url('images/blue-box.jpg');
border:1px #003366;
box-shadow: 4px 5px 2px #888888;
}
JavaScript: JavaScript:
$(document).ready(function() {
var preload = [
'css/images/blue-box.jpg',
'css/images/gray-box.jpg'
];
preloadImages(preload);
function preloadImages(arrayOfImages) {
$(arrayOfImages).each(function(){
(new Image()).src = this;
});
}
$box = "#box";
$($box).mouseover(function()
{
$($box).css("background-image", "url(' " + preload[1] + " ')");
});
}); });
Thanks in advance, 提前致谢,
Diego. 迭戈
move the preload array to global. 将预加载数组移到全局。
var preload = [
'css/images/blue-box.jpg',
'css/images/gray-box.jpg'
];
and call like this 像这样打电话
$(function(){
preloadImages(preload);//call the preload functions
})
And I suggest you to cache the static content resources.
我建议您
cache the static content resources.
such as images, css. 例如图片,CSS。 so that browser will read the cached images.
以便浏览器读取缓存的图像。
HTTP 304 Not Modifi
ed status). HTTP 304 Not Modifi
状态)。 until unless user wants to clear the cache.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.