简体   繁体   English

在悬停事件中更改图像时如何避免新的请求?

[英]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. 以便浏览器读取缓存的图像。

  1. By using cache, whenever you request new image, based on your cache setting, Image will get appended a Expire headers for the response. 通过使用缓存,每当您请求新图像时,根据您的缓存设置,Image都会附加一个Expire标头用于响应。
  2. When the user request for the same image again, browser will load it from the cached images. 当用户再次请求相同的图像时,浏览器将从缓存的图像中加载它。 (browser will issse 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.

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