当我们完成加载和淡化图片时,我会附加一张大图片。我的问题是当有多个图像时。然后它只是被替换的最后一个小图像(第一个图像)。我似乎无法弄清楚如何将它们分开。通过数据属性检索src
个网址。 Codepen with two images。 (with one image it works as intended)。
window.onload = function() {
var ImageBlur = function (element) {
var self = this;
this.element = element;
this.$element = $(element);
};
var placeholder = $('.js-image-blur', this.$element);
var small = $('.js-small-image', placeholder);
// Load large image
var imgLarge = new Image();
imgLarge.src = placeholder.data('largeimage');
imgLarge.className = "is-large-image";
imgLarge.onload = function () {
$(imgLarge).addClass('is-loaded');
// Remove small image
setTimeout(function(){
$(small).remove();
}, 1200);
};
$(imgLarge).each(function() {
placeholder.append(this);
});
return ImageBlur;
};
答案 0 :(得分:1)
我会像那样重写代码:
$(function() {
$(".js-image-blur").each(function() {
var $this = $(this);
var $smallImage = $(".js-small-image", $this);
var $largeImage = $("<img>").attr({
src: $this.data("largeimage"),
class: "is-large-image"
}).load(function() {
$(this).addClass("is-loaded");
setTimeout(function() {
$smallImage.remove();
}, 1200);
});
$this.append($largeImage);
});
});
&#13;
.image-blur {
background-color: transparent;
background-size: cover;
background-repeat: no-repeat;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
overflow: hidden;
}
.image-blur img {
position: absolute;
top: 50%;
left: 50%;
min-height: 100%;
width: auto;
min-width: 100%;
transition: opacity 1s linear;
-ms-transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
.image-blur img.small-image {
-webkit-filter: blur(20px);
filter: blur(20px);
position: absolute;
}
.image-blur img.is-large-image {
opacity: 0;
}
.image-blur img.is-loaded {
opacity: 1;
}
body {
margin: 3em 0;
background: silver;
}
.container {
position: relative;
margin: 3em auto;
min-width: 320px;
min-height: 560px;
border-top: 3px solid black;
border-bottom: 3px solid black;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="container">
<div class="image-blur js-image-blur" data-component="image-blur" data-largeimage="https://s3-us-west-2.amazonaws.com/s.cdpn.io/67710/1600-full.jpg">
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/67710/1600-small.jpg" alt="" class="small-image js-small-image" />
</div>
</section>
<section class="container">
<div class="image-blur js-image-blur" data-component="image-blur" data-largeimage="https://s3-us-west-2.amazonaws.com/s.cdpn.io/67710/1600-2-full.jpg">
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/67710/1600-2-small.jpg" alt="" class="small-image js-small-image" />
</div>
</section>
&#13;
请参阅updated Codepen。
答案 1 :(得分:0)
如果您想以静默方式加载图像并淡入它们,一个简单的解决方案就是:
<img class="load-fade" src="url" />
在你的JavaScript中:
$('.load-fade').hide().load(function() {
$(this).fadeIn(1000);
});