jQuery 图片加载后淡入淡出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9845774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:22:51  来源:igfitidea点击:

Fade in images after they have loaded

jqueryimageload

提问by Andy

I found this code to achieve the desired effect and tried it on JSFiddle

我发现这段代码达到了预期的效果并在JSFiddle上试了一下

http://jsfiddle.net/AndyMP/7F9tY/366/

http://jsfiddle.net/AndyMP/7F9tY/366/

It seems to work in that it fades the image in after it has loaded. Then I tried it in a webpage and it didn't work the same way, loading the image first rather than fading it in. Although sometimes it seemed like it was fading in at the same time as it loaded.

它似乎起作用,因为它在加载后淡入图像。然后我在网页中尝试了它,但它并没有以同样的方式工作,首先加载图像而不是淡入。尽管有时看起来它在加载的同时淡入。

Is there a more reliable way of achieving this, preferably by amending this code if possible?

是否有更可靠的方法来实现这一点,最好是在可能的情况下修改此代码?

$("#image").ready(function(){ $("#preload").fadeIn(1000); });

$("#image").ready(function(){ $("#preload").fadeIn(1000); });

回答by jfriend00

The only reliable way to fadeIn()an image that is in your actual HTML markup is to set an onloadhandler in the HTML markup like this:

获取fadeIn()实际 HTML 标记中图像的唯一可靠方法是在 HTML 标记中设置onload处理程序,如下所示:

<div id="image">
    <img id="preload" onload="fadeIn(this)" src="https://photos.smugmug.com/photos/i-NLws86p/0/b356e43a/L/i-NLws86p-S.jpg" style="display:none;" />
</div>

<script>
// this function must be defined in the global scope
window.fadeIn = function(obj) {
    $(obj).fadeIn(1000);
}
</script>

Working demo here: https://jsfiddle.net/jfriend00/X82zY/

这里的工作演示:https: //jsfiddle.net/jfriend00/X82zY/

Doing is this way, you don't need to give each image an id or class. Just set the style and the event handler in the markup.

这样做,你不需要给每个图像一个 id 或类。只需在标记中设置样式和事件处理程序。

The reason you have to put the event handler in the markup is that if you wait until your page's javascript runs, it may be too late. The image may already be loaded (particularly if it's in the browser cache) and thus you may have missed the onloadevent. If you put the handler in the HTML markup, you will not miss the onloadevent because the handler is assigned before the image starts loading.

您必须将事件处理程序放在标记中的原因是,如果您等到页面的 javascript 运行,则可能为时已晚。图像可能已经加载(特别是如果它在浏览器缓存中),因此您可能错过了该onload事件。如果将处理程序放在 HTML 标记中,则不会错过该onload事件,因为在图像开始加载之前已分配处理程序。

If you don't want to put event handlers in the javascript, then you can do something like this where you use a placeholder for the image in the actual HTML and you use javascript to create the actual image tags and insert them and pull the image URL from the placeholder:

如果您不想在 javascript 中放置事件处理程序,那么您可以执行以下操作,在实际 HTML 中为图像使用占位符,然后使用 javascript 创建实际图像标签并插入它们并拉取图像占位符中的 URL:

<div>
    <span class="fadeIn" data-src="https://photos.smugmug.com/photos/i-NLws86p/0/b356e43a/L/i-NLws86p-S.jpg"></span>
</div>

<script>
$(document).ready(function() {
    $(".fadeIn").each(function() {
        var src = $(this).data("src");
        if (src) {
            var img = new Image();
            img.style.display = "none";
            img.onload = function() {
                $(this).fadeIn(1000);
            };
            $(this).append(img);            
            img.src = src;
        }
    });
});
</script>

Working demo: https://jsfiddle.net/jfriend00/BNFqM/

工作演示:https: //jsfiddle.net/jfriend00/BNFqM/

The first option will get your images loaded a little quicker (because image loading starts immediately upon page parsing), but the second option gives you more programmatic control over the process.

第一个选项将使您的图像加载速度更快(因为图像加载会在页面解析时立即开始),但第二个选项可以让您对过程进行更多的编程控制。

回答by Robbendebiene

Pure java script and CSS solution:

纯java脚本和CSS解决方案:

Using the transitions effect with opactiy.

使用 opactiy 的过渡效果。

const images = document.getElementsByTagName("img");
for (let image of images) {
  image.addEventListener("load", fadeImg);
  image.style.opacity = "0";
}

function fadeImg () {
  this.style.transition = "opacity 2s";
  this.style.opacity = "1";
}
<img src="http://lorempixel.com/400/200/">
<img src="http://lorempixel.com/g/400/200/">
<img src="http://lorempixel.com/400/200/sports/">

回答by Felix Engelmann

Maybe interesting for people who find this question and use angular.js:

对于发现这个问题并使用 angular.js 的人来说,这可能很有趣:

I've written a small directive which does the job quite well.

我写了一个小指令,它可以很好地完成这项工作。

JS:

JS:

.directive('imgFadeInOnload', function () {
    return {
      restrict: 'A',
      link: function postLink(scope, element, attr) {
        element.css('opacity', 0);
        element.css('-moz-transition', 'opacity 2s');
        element.css('-webkit-transition', 'opacity 2s');
        element.css('-o-transition', 'opacity 2s');
        element.css('transition', 'opacity 2s');
        element.bind("load", function () {
          element.css('opacity', 1);
        });
        element.attr('src', attr.imgFadeInOnload);
      }
    };
  });

HTML:

HTML:

<img img-fade-in-onload="{{imgSrc}}" src="">

By setting srcnot in the HTML but in the directive code the problem mentioned by jfriend00 (handler is attached after the onloadis fired) is solved.

通过src不在 HTML 中而是在指令代码中进行设置,jfriend00 提到的问题(处理程序在onload触发后附加)得到解决。

回答by DefyGravity

html

html

<div id="image">
    <img id="preload" src="http://farm8.staticflickr.com/7227/7007769551_3b5b1640ea_b.jpg" style="display:none;" />
</div>

javascript

javascript

.ready() does not fire they way you think it does, see the 'load'jQuery event handler

.ready() 不会按照您认为的方式触发,请参阅“加载”jQuery 事件处理程序

$("#preload").load(function(evt){
      $(this).fadeIn(1000);
});

回答by stewe

fadeInshould be called after the image has loaded. Here is an example: http://jsfiddle.net/mYYym/

fadeIn应该在图像加载后调用。这是一个例子:http: //jsfiddle.net/mYYym/

回答by squarecandy

Here's a css transition and javascript solution based on @jfriend00's answer and similar to the approach of @Robbendebiene:

这是一个基于@jfriend00 的回答并类似于@Robbendebiene 的方法的 css 转换和 javascript 解决方案:

  • provides fallbacks to display the image if js is turned off
  • only the one bit of inline javascript is required onload="this.style.opacity=1"
  • all animation is CSS, no need for jQuery or complex javascript
  • 如果 js 关闭,则提供后备以显示图像
  • 只需要一位内联 javascript onload="this.style.opacity=1"
  • 所有动画都是 CSS,不需要 jQuery 或复杂的 javascript

img.fadein {
  opacity: 1;  /* fallback in case of no js */
  transition: opacity 500ms ease;
  max-width: 100%;
  height: auto;
}
.js img.fadein {
  opacity: 0; /* start with hidden image if we have js */
}
<!-- use moderinr to provide the "js" class on the html element -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js"></script>
<img class="fadein" onload="this.style.opacity=1" src="http://lorempixel.com/1500/1500/">