我怎样才能预加载悬停状态的图像以使背景立即更改,而不是在几秒钟后.即背景必须在用户将鼠标悬停在特定元素之前加载。
该网站可以在 http://www.paradisoperduto.co.uk/
查看到目前为止,我对编码非常满意,所以想知道是否有相对简单的更改来实现这一点。非常感谢。
<!-- background change -->
<script type="text/javascript">
$(document).ready(function() {
$('#hoverarea').hover(function() {
$('body').addClass('hover');
}, function(){
$('body').removeClass('hover');
});
});
</script>
<!-- background change-->
<div id="hoverarea"><a href="comingsoon.html"> <img src="images/blank.png" onmouseover="playSound('audio/apple2.mp3');"> </a></div>
body {
background-image:url('../images/blackandwhite.gif');
background-position:50% 20px;
background-attachment:fixed;
background-repeat: no-repeat;
background-color:black;
height:714px;
width:1024;
}
#hoverarea {
position:absolute;
width:400px;
height:400px;
top:300px;
right:20px;
z-index:2000;
}
.hover {
background-image:url('../images/colour.gif');
}
li a:hover + img {
left: 0px;
}
你指的是大背景图像。 问题是,由于页面上的元素太少,用户可能会在预加载第二个图像之前将鼠标悬停在图像上。 毕竟,这是一个很大的形象。
你可以尝试的一件事是CSS精灵。那里的概念是将两个图像组合成一个高图像,以便将其全部加载为一个图像。然后,在你的 css 中,你做这样的事情:
#hoverarea {
background-image: url('../images/backgroundimage.gif');
background-position: center top;
}
#hoverarea:hover {
background-position: center bottom;
}
这样,您所做的只是更改一个图像的 css 定位,而不是使用繁琐的 JavaScript 解决方案来预加载和注入第二个图像。
您可以在 JavaScript 中等待此图像 - 在我的网站上,我正在使用"缓存列表"包含要在显示网站之前预加载的图片的 URL - 如果你要在 js 中制作新的图像元素并给它这张图片的 src,当 onload 事件将触发时 - 浏览器将缓存此图像,以便在它出现在任何其他地方时立即显示。 这是我网站的代码, 但我想很清楚它是如何工作的:
function cache(input, prefix, primary, cback){
this.cback = cback
this.tab=[];
var tmp = input;
var cur;
for (var i = 0; i < tmp.length; i++)
{
if (tmp[i][0] == primary)
cur = i;
}
if (cur != undefined)
{
this.size = tmp[cur][1].length;
if (this.size == 0)
this.cback();
for (var i = 0; i < this.size; i++)
{
var img = document.createElement('img');
img.src = prefix+tmp[cur][1][i];
img.onload = this.imgReady.bind(this);
img.onerror = this.imgError.bind(this);
this.tab.push(img);
console.log('caching:', img.src);
}
tmp.splice(cur, 1);
return;
}
this.cback();
}
cache.prototype = {
counter:0,
size:0,
tab:0,
cback:function(){return;},
imgReady:function(element){
this.counter++;
if (this.counter == this.size){
storeCache(this.tab)
this.cback(this.tab);
}},
imgError:function(){
DEBUG.innerHTML+='[ERROR] cache error!<br>';
console.log('cache error...');
this.imgReady();}
}
缓存列表如下所示:
[
[
'main',
[
'/pictures/party.png',
'/pictures/icon.png',
'/pictures/+1.png',
'/pictures/splash.jpeg',
'/pictures/logo_compact.png',
'/pictures/dj.png',
'/pictures/sign.png',
'/textures/main.jpg',
'/textures/shadow.png',
'/textures/smallshadow.png',
'/textures/outlineH.png',
'/textures/outlineV.png',
'/textures/bg.jpg',
'/textures/alt.jpg'
]
],
[
'theme_selector',
[
'/../uni/p1.png',
'/../uni/p1a.png',
'/../uni/p2.png',
'/../uni/p2a.png',
'/../uni/p3.png',
'/../uni/p3a.png',
]
],
...
]
实际上我为所有子网站使用一个缓存文件,这就是为什么缓存列表中有"主"或"theme_selector"标识符的原因(它们作为前缀参数传递)
所以一般的想法是为每个重要的图片创建图像元素,并在它们触发onload事件(或onerror)后继续操作,因为这样它们已经被浏览器缓存并立即显示在我们想要的任何地方