[英]Pre-load Jquery hover images
Right now I am building a map of the US, and when you hover over any given state, I am replacing the image with an image of a different color.现在我正在构建美国地图,当你将鼠标悬停在任何给定的州时,我正在用不同颜色的图像替换图像。
My problem is that the way I am currently doing things, the image is being replaced and a new image loaded on hover.我的问题是我目前做事的方式,正在替换图像并在悬停时加载新图像。
I have the HTML laid out as:我将 HTML 布局为:
<img class="state" id="alaska" src="img/united-states_Alaska.png" alt="alaska">
<img class="state" id="hawaii" src="img/united-states_hawaii.png" alt="hawaii">
And the jQuery I am using is:我正在使用的 jQuery 是:
$('.interactive-map img').each(function(e){
var src = $(this).attr('src');
$(this).hover(function(){
$(this).attr('src', src.replace('.png', '-hover.png'));
}, function(){
$(this).attr('src', src);
});
});
I am curious if there is another way to either preload the images with JavaScript, or make it so that there isn't a new request for image every time I hover.我很好奇是否有另一种方法可以使用 JavaScript 预加载图像,或者使每次悬停时都没有新的图像请求。 I would like to not have to change the HTML or CSS much and optimize it in JavaScript.我希望不必过多更改 HTML 或 CSS 并在 JavaScript 中对其进行优化。
Add your images to the DOM on page load but in hidden state, then they get cached在页面加载时将图像添加到 DOM 但处于隐藏状态,然后它们会被缓存
$(function() {
var images = ['url/to/your/jpg1.jpg', 'ur/to/your/png2.png'];
var d = document.createElement("div");
d.style.display = 'none';
document.body.appendChild(d);
for (var i in images)
{
var img = document.createElement("img");
img.src = images[i];
d.appendChild(img);
}
});
Have two image tags and set the first image's display: block
.有两个图像标签并设置第一个图像的display: block
。 Set the second image's display: none
.设置第二张图片的display: none
。
Then on hover you switch the them.然后在悬停时切换它们。 It is as easy as that.就是这么简单。
Example:例子:
var preload = new createjs.LoadQueue();
preload.addEventListener("fileload", handleFileComplete);
preload.loadFile('http://createjs.com/images/404/gBot-confused.jpg');
function handleFileComplete(event) {
document.body.appendChild(event.result);
}
Another interesting post using JS and AJAX: Preloading另一个使用 JS 和 AJAX 的有趣帖子: 预加载
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.