在页面加载,CSS上加载图像

时间:2014-02-15 09:45:03

标签: javascript html css image

我最近问了一个关于使用Java Script将图像用作按钮的问题。答案我得到了我的反对使用CSS而且工作正常。但是我使用的图像大约需要0.2秒才能加载。

在我使用此代码之前,我的页面在开始时加载了所有图像,然后是一个JS脚本来修改某些鼠标事件下图像的zIndex,但这会覆盖href链接并且无法工作。

使用新代码所有功能都可以正常工作,因此每次只加载第一个Image加载时,另外2个我在触发鼠标事件时在加载时使用此图像。这意味着在执行操作时按钮会闪烁。如何修改此代码以在页面加载的同时加载图像?

此处代码:http://jsbin.com/casoy/12/edit?html,css,output

我以为我应该显示旧代码...... http://jsbin.com/casoy/13/edit?html,css,js,output

1 个答案:

答案 0 :(得分:3)

在触发css样式之前,不会进行下载图像的调用。

有几种方法可以将html组织成您喜欢的内容,

- here is a crude example using your code 以显示原则。

<强> MARKUP

<div class="preload1"></div>
<div class="preload2"></div>

<a href="http://officialacescottie.co.uk/Home/Home.html">click me</a>

* CSS *

a {
  display: block;
  width: 600px;
  height: 114px;
  background-image:url("/Buttons/Home.gif");
  text-indent: -9999px;
  outline: 0;
}
a:hover, .preload1 {
  background-image:url("/Buttons/HomeP.gif");
}
a:active, .preload2 {
  background-image:url("/Buttons/HomeC.gif");
}
/* hide these off page in a way that 
   the browser will still call the background-image */
.preload2, .preload1 {
  position:absolute; left:-9999px; top:-9999px;
}

/* image urls are shortened here only so it presents better on SO */

这显示了一个基本原则,即当触发a:hover时,引用的背景图像已经有机会“预加载”到浏览器缓存中。

相关问题