我尝试使用javascript预加载图片:
$(document).ready(function () {
preloadImages(
['../../Content/Resources/close_mouse_over.png',
'../../Content/Resources/close.png']);
});
function preloadImages(sources) {
var image = new Array();
for (var i = 0; i < sources.length; i++) {
image[i] = new Image();
image[i].src = sources[i];
}
}
function mouseOverForImage(imgId, imgSrcs) {
document.getElementById(imgId).src = imgSrcs;
}
在Html中:
<input type="image" src="../../Content/Resources/close.png" name="Action" value="Save" onmouseover="mouseOverForImage('close', '../../Content/Resources/close_mouse_over.png')"
onmouseout = "mouseOverForImage('close', '../../Content/Resources/close.png')" id="close" title = "Close" />
但鼠标悬停后请求仍然发送到服务器。不适用于chrome
答案 0 :(得分:1)
正如我在评论中所指出的那样,您正在将数组数组传递给preLoadImages方法。
因此,您将数组传递给image[i].src
,这意味着它不会被加载。
尝试
$(document).ready(function () {
preloadImages(
['../../Content/Resources/close_mouse_over.png', '../../Content/Resources/close.png']);
});
function preloadImages(sources) {
var image = new Array();
for (var i = 0; i < sources.length; i++) {
image[i] = new Image();
image[i].src = sources[i];
}
}
function mouseOverForImage(imgId, imgSrcs) {
document.getElementById(imgId).src = imgSrcs;
}
或者,如果你想保留数组的数组,那么使用
function preloadImages(sources) {
var image = new Array();
for (var i = 0; i < sources.length; i++) {
image[i] = new Image();
image[i].src = sources[i][0];
}
}
编辑,进一步调查后,可能的原因是preloadImages
在预加载图片后销毁image
数组。
试试这个:
function preloadImages(sources) {
window.preloadedImages = new Array();
for (var i = 0; i < sources.length; i++) {
window.preloadedImages[i] = new Image();
window.preloadedImages[i].src = sources[i];
}
}
这会将预加载的图像存储在窗口对象中,允许它们正确预加载。
希望有帮助吗?