Javascript预加载图像的css背景图像更改 [英] Javascript preload images for css background-image change

查看:96
本文介绍了Javascript预加载图像的css背景图像更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个网站,要求一个div的背景图片在链接悬停时更改。

I am developing a website which requires the background image of a div to change on hover of a link.

它的工作方式是:

<a href="index.php" title="Home ">
 <li id="current">
   Home<br \>
   <span class="nav_desc">Text text</span>
 </li>
</a>
<a href="about.php" title="About" id="about-link" 
   onmouseover="hover('about');" 
   onmouseout="hoverClear();">
 <li id="about">
  About<br \>
  <span class="nav_desc">About me</span>
 </li>
</a>
<a href="more.php" title="More" 
   onmouseover="hover('portfolio');" 
   onmouseout="hoverClear();">
 <li id="more">
  More<br \>
  <span class="nav_desc">More More More
  </span>
 </li>
</a>

js:

function hoverClear(){
    $('.navReflect').css("background-image", "url(images/"+page+"/reflect.png)");
}
function hover(hover){
    $('.navReflect').css("background-image", "url(images/"+page+"/reflect-"+hover+".png)");
}

因此,当链接被悬停时,它会执行一项功能来更改div背景图片。但是问题是当页面第一次加载和链接第一次徘徊缓慢加载的图像。

So, when a link is hovered it does a function to change div background image. But the issue is when the page is first loaded and the links hovered for the first time there is slow loading of the image.

但是一旦他们加载它无缝工作。我期望这是一个问题,它需要加载。

But once they have loaded it works seamless. I expect this is an issue with it needed to be loaded. So is there a way I can preload the images before hand and still use the same method for the hover.

推荐答案

堆叠图片作为一个图像,然后添加一个类,将图像的背景属性移动到适当的偏移。

Stack your images as one image, and then add a class that shifts the image's background property to the appropriate offset.

这不仅会将多个图片转换为一个HTTP请求,还意味着您不必费心编写代码来预加载悬停

Not only does this turn multiple images into one HTTP request, it also means you don't have to bother writing code to preload the hover state of the images.

这称为 sprite sheet

这篇关于Javascript预加载图像的css背景图像更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆