Html/JavaScript预加载图像

Html/JavaScript预加载图像,javascript,html,css,flicker,Javascript,Html,Css,Flicker,我有一个网页与一些img链接。当图像处于悬停状态时,我会更改页面中div的背景。javascript代码如下所示: function hover(element) { if(element.id=="first"){ element.setAttribute('src', './images/first_active_2.png'); back.style.backgroundImage = 'url(./images/1.png)'; text.src

我有一个网页与一些img链接。当图像处于
悬停
状态时,我会更改页面中div的背景。javascript代码如下所示:

function hover(element) {
  if(element.id=="first"){
      element.setAttribute('src', './images/first_active_2.png');
      back.style.backgroundImage = 'url(./images/1.png)';
      text.src = './images/text_first_active.png';
  }
  if(element.id=="second"){
      element.setAttribute('src', './images/second_active_2.png');
      back.style.backgroundImage = 'url(./images/3.png)';
      text.src = './images/text_second_active.png';
  }
}

function unhover(element) {
  if(element.id=="first"){
    element.setAttribute('src', './images/first_inactive_2.png');
    text.src = './images/text_first_inactive.png';
  }
  if(element.id=="second"){
    element.setAttribute('src', './images/second_inactive_2.png');
    text.src = './images/text_second_inactive.png';
  }
}
以及html代码:

<div id="back"/>
  <a>
    <img id="first" src="images/first_inactive_2.png" onmouseover="hover(this);" onmouseout="unhover(this);" />
  </a>
  <a>
    <img id="second" src="images/second_inactive_2.png" onmouseover="hover(this);" onmouseout="unhover(this);"/>
  </a>

一切都很好,但有时背景图像会闪烁。我想我必须预加载两个
images/1.png
images/2.png
,但我不知道如何正确地进行预加载。是否有正确的方法使图像不闪烁?

var img=new Image(); img.src=“/path/to/image.jpg”


这可能在某个地方的window.load或dom:ready事件中,通过这种方式可以预加载图像。

几周前,我遇到了类似的问题。您可以使用“onload”事件预加载图像:

var tmpNewImg = new Image();
tmpNewImg.onload = function () {
  var yourDiv = document.getElementById('picture');
  yourDiv.style.backgroundImage = 'url(' + this.src + ')';
}

tmpNewImg.src = '/your/background/image.jpg';

这有助于解决我的问题。但是我没有在本例中测试代码。

使用css
:hover
和hover image in
:after
伪元素:

div {
    background: url(http://keddr.com/wp-content/uploads/2013/12/google.png);
    width:300px;
    height: 200px;
    background-size: 100% 100%;
}

div:after {
    content: '';
    font: 0/0 a;
}

div:hover,
div:after {
    background-image: url(http://hi-news.ru/wp-content/uploads/2013/11/0111.jpg);
}

这已经被问过好几次了。参见,例如,更好地使用