【问题标题】:Best way to change CSS Background Image on hover在悬停时更改 CSS 背景图像的最佳方法
【发布时间】:2017-07-17 06:20:39
【问题描述】:

我有一个全屏背景图像,当我将鼠标悬停在 div 上时,我需要将其换成其他图像。我正在使用 jQuery 执行此操作 - 问题是加载时间相当长。

有没有一种方法可以使图像在第一次悬停时几乎立即出现?我的代码如下:

$("#hover-bg-2").mouseover(function() {
  $("#container").css("background", "url(/assets/image-2.jpg)");
  $("#container").css("-webkit-background-size", "cover");
  $("#container").css("-moz-background-size", "cover");
  $("#container").css("-o-background-size", "cover");
  $("#container").css("background-size", "cover");
});
#container {
  width: 100vw;
  height: 100vh;
  
  /* ORIGINAL IMAGE BEFORE CHANGE */
  background: url(/assets/image-1.jpg) no-repeat center center fixed;
  
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div class="bg-hover">
    <div id="hover-bg-2" style="cursor: pointer;">
      <p>BG 2</p>
    </div>
  </div>
</div>

【问题讨论】:

  • 图片的尺寸是多少?
  • 我要注意的一点是,没有必要在 JavaScript 中继续设置背景属性,因为只有 URL 会发生变化。我还将修改 CSS 以使用 background-image 而不是 background,而是单独指定其他背景属性,因为您只是换出了 URL,因此无需重复该信息,例如background-positionbackground-repeat
  • 图片为 1200 x 675 @lomboboo
  • @nickrigby 感谢您指出这一点 - 问题是我尝试只是换掉 URL,除非我明确重写相同的规则,否则定位不会保持不变
  • @SamYoungNY 应该,但您需要确保您指定只是更改 JavaScript 中的 background-image,例如$("#container").css("background-image", "url(/assets/image-2.jpg)");

标签: jquery html css caching


【解决方案1】:

您可以在 CSS3 中做到这一点(大多数浏览器现在应该支持这一点)。即使 javascript 不会,它也将具有工作的优势。

你可以这样做:

.classToChange{
    background: "oldbackground.jpg"
}

.classToHoverOver:hover .classToChange{
      background: "newbackground.jpg"
}

【讨论】:

    【解决方案2】:

    Link Prefetching 中的&lt;head&gt; 是减少加载时间的最简单方法,无论您使用哪种交换方法方法。

    <link rel="prefetch" href="/images/big.jpeg">
    

    我不知道为什么 Safari 不支持这个,但是the other browsers do

    【讨论】:

      【解决方案3】:

      您可以使用鼠标事件更改容器的class,最初加载css,只需使用Jquery 更改容器的class

      例如

      $("#hover-bg-2").hover(function() {
        $('#container')
          .removeClass("class_default")
          .addClass("other");
      }, function() {
        $('#container')
          .removeClass("other")
          .addClass("class_default");;
      });
      .class_default {
        /* your style goes here */
        background: red;
      }
      .other{
      background:green;
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <div id="container" class="class_default">
      
        <div class="bg-hover">
          <div id="hover-bg-2" style="cursor: pointer;">
            <p>BG 2</p>
          </div>
      
        </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-31
        • 2020-07-24
        • 1970-01-01
        • 2019-10-11
        • 2019-01-21
        • 2013-11-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多