【问题标题】:Html/JavaScript preload images [duplicate]Html/JavaScript 预加载图像 [重复]
【发布时间】:2023-03-18 02:27:01
【问题描述】:

我有一个带有一些 img 链接的页面。当图像处于hover 状态时,我更改了页面内 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.pngimages/2.png,但我不知道如何正确执行。有没有正确的方法让图像不闪烁?

【问题讨论】:

标签: javascript html css flicker


【解决方案1】:

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

这可能在某个地方的 window.load 或 dom:ready 事件中,这样您就可以预加载图像。

【讨论】:

    【解决方案2】:

    :after伪元素中使用css :hoverpreload悬停图片:

    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);
    }
    

    【讨论】:

      【解决方案3】:

      几周前我遇到了类似的问题。您可以使用“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';
      

      这有助于解决我的问题。但是我没有测试这种情况下的代码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多