加载后淡入背景图像(无 jquery),同时仍使用媒体查询替换不同屏幕尺寸的图像

Fade in background-image once it loads (no jquery) while still using media queries to replace images for different screen sizes

我整晚都在看书,似乎无法就最好的方法是什么给出任何具体的答案。我知道的两件事是这些——

加载图像时淡入淡出:

像这样使用图像包装器和 <img> 标签:

<div class="imageWrapper">
    <img src="img.jpg" alt="" onload="imageLoaded(this)">
</div>

并且 css 看起来像

.imageWrapper {
  opacity: 0
}

.loaded {
  opacity: 1
}

然后在你的 js 文件中加入类似

的内容
var imageLoaded = (img) => {
    var imgWrapper = img.parentNode;
    imgWrapper.className += ' loaded';
}

用于根据屏幕尺寸加载不同的图像

@media screen only and (min-device-width: 0) and (max-device-width: 450px) {
  .backgroundImage {
    background: url('small_background_image.jpg');
  }
}

@media screen only and (min-device-width: 451px) and (max-device-width: 1024px) {
  .backgroundImage {
    background: url('medium_background_image.jpg');
  }
}

@media screen only and (min-device-width: 1025px) {
  .backgroundImage {
    background: url('large_background_image.jpg');
  }
}

我的问题

我可以分别做这两件事(加载图像时淡入淡出,当浏览器检测到较小的屏幕尺寸时更改背景图像),但是我似乎无法找到包含 both 的解决方案。我需要能够为不同的屏幕尺寸指定不同的图像,并且还能够检测何时加载该图像并将其淡入。

有什么好的方法吗?

我的解决方案:

我最终使用了 guest271314's 的变体来加载正确的图像。这适用于每个浏览器的所有最新版本,并且非常容易实现。

首先,我在开始 <body> 标记的正下方放置了一个内联脚本,这样如果我的浏览器加载我的 js 文件速度很慢,它仍然可以立即加载图像。

<body>
    <script>
        function imageLoaded(img) {
            if ((" " + img.className + " ").indexOf(" "+'loaded'+" ") > -1 ) {
            return true;
            } else {
                img.className += ' loaded';
            }
        }
    </script>

然后我的 <picture> 标签是这样的:

<picture class="backgroundContainer">
    <source srcset="img-1024.jpg" media="(min-width: 0px) and (max-width:1024px)">
    <source srcset="img-1920.jpg" media="(min-width: 1025px) and (max-width: 1920px)">
    <source srcset="img-2560.jpg" media="(min-width: 1921px)">
    <img class="backgroundImage" onload="imageLoaded(this)" src="img-1920.jpg" alt="">
</picture>

我的 sass 看起来像这样:

@keyframes fadeIn
  0%
    opacity: 0
  100%
    opacity: 1

.backgroundContainer
  width: 100%
  height: 100%

.backgroundImage
  opacity: 0

.loaded
  opacity: 1
  animation: fadeIn 3s

这允许浏览器(不考虑速度)等到尺寸正确图像加载完成,然后淡出它超过 3s,使用旧浏览器的 <img> 标签安全回退。

I basically need to be able to fade in a background-image when it loads, or be able to change an <img> tag's src before it loads depending on screen size, or do something that incorporates both of these things using a method I'm unaware of.

您可以使用css content 属性 值设置为 url() 功能有 URL 个图像显示,或更改显示的图像源; css animation@keyframes 在加载源图像时淡入 background-image

html

<picture class="backgroundImage"></picture>

css

.backgroundImage {
  opacity: 0; /* set `opacity` to `0` */
  width: 50px;
  width: 50px;
  content: url(http://lorempixel.com/50/50/technics); /* set intial image */
  animation-name: fadein;
  animation-iteration-count: 1;
  animation-duration: 2500ms;
  animation-fill-mode: both;
}

@keyframes fadein {
  to {
    opacity: 1; /* fade in image */
  }
}
/* set media queries */
@media screen only and (min-device-width: 0) and (max-device-width: 450px) {
  .backgroundImage {
    opacity: 0; /* set `opacity` to `0` */
    content: url(http://lorempixel.com/50/50/cats); /* set image */
    animation-name: first;
  }
  @keyframes first {
    to {
      opacity: 1; /* fade in image */
    }
  }
}

@media screen only and (min-device-width: 451px) and (max-device-width: 1024px) {
  .backgroundImage {
    opacity: 0; /* set `opacity` to `0` */
    content: url(http://lorempixel.com/50/50/city); /* set image */
    animation-name: second;
  }
  @keyframes second {
    to {
      opacity: 1; /* fade in image */
    }
  }
}

@media screen only and (min-device-width: 1025px) {
  .backgroundImage {
    opacity: 0; /* set `opacity` to `0` */
    content: url(http://lorempixel.com/50/50/sports); /* set image */
    animation-name: third;
  }
  @keyframes third {
    to {
      opacity: 1; /* fade in image */
    }
  }
}

jsfiddle https://jsfiddle.net/yayd5Lma/3

您应该为此目的使用 css3 动画。

@-webkit-keyframes fadeIn {
            0% {opacity: 0;}
            100% {opacity: 1;}
         }

         @keyframes fadeIn {
            0% {opacity: 0;}
            100% {opacity: 1;}
         }

         .fadeIn {
            -webkit-animation-name: fadeIn;
            animation-name: fadeIn;
         }

我会在我的标记中加载所有图像并为媒体查询分配 类:

<div class="imageWrapper">
    <img class="small" src="img_small.jpg" onload="imageLoaded(this)">
    <img class="med" src="img_med.jpg" onload="imageLoaded(this)">
    <img class="large" src="img_large.jpg" onload="imageLoaded(this)">
</div>

然后根据需要使用媒体查询隐藏它们:

@media screen only and (min-device-width: 0) and (max-device-width: 450px) {
  .imageWrapper .large, .imageWrapper .medium { display: none; }
}

@media screen only and (min-device-width: 451px) and (max-device-width: 1024px) {
  .imageWrapper .large, .imageWrapper .small { display: none; }
}

@media screen only and (min-device-width: 1025px) {
  .imageWrapper .small, .imageWrapper .medium { display: none; }
}

edit #2: an updated fiddle of progress so far: https://jsfiddle.net/c5hy0g8r/11

The problem is still that on slow network conditions, using css 'content' property will still load in chunks as images usually do. The usual method of onload="imageLoaded(this)" will not work on an img or picture that has its content generated by css content: url('img.jpg') property.

您可以使用具有一个或多个 <source> 元素且 srcset 属性设置为图像源的 <picture> 元素,对应 [=25] 时应显示在 <img> =] 设置为有效媒体查询列表的属性与环境相匹配。

<img> 元素的 onload 事件中,将父元素 opacity 设置为 0;使用 requestAnimationFrame() 将元素的 opacity0 动画化到 1.

<!DOCTYPE html>
<html>

<head>
  <style>
    .imageWrapper {
      opacity: 0;
    }
  </style>
</head>

<body>

  <picture class="imageWrapper">
    <source srcset="http://lorempixel.com/50/50/technics" media="(min-width: 0px) and (max-width:150px)">
    <source srcset="http://lorempixel.com/50/50/city" media="(min-width: 151px) and (max-width: 300px)">
    <source srcset="http://lorempixel.com/50/50/nature" media="(min-width: 301px) and (max-width:450px)">
    <source srcset="http://lorempixel.com/50/50/sports" media="(min-width: 451px) and (max-width:600px)">
    <source srcset="http://lorempixel.com/50/50/animals" media="(min-width: 601px)">
    <img width="50px" height="50px" onload="imageLoaded(this)" src="null" alt="">
  </picture>
  <figcaption></figcaption>
    <script>
    const num = 1/60;
    var fx = null;
    var caption = document.querySelector("figcaption");
    var imageLoaded = (img) => {
      caption.innerHTML = "";
      cancelAnimationFrame(fx);
      var n = 0;
      var imgWrapper = img.parentNode;
      imgWrapper.style.opacity = 0;
      fx = requestAnimationFrame(function animate() {
        console.log(n);
        if (n < 1) {
          n += num;
          imgWrapper.style.opacity = n;
          fx = requestAnimationFrame(animate);
        } else {
          caption.innerHTML = img.currentSrc.slice(img.currentSrc.lastIndexOf("/") + 1);
          console.log("complete");
        }
      })
    }
  </script>
</body>
</html>

plnkrhttp://plnkr.co/edit/RWSc6J3kUUJPUZsrpagi?p=preview