1 回答
TA贡献1995条经验 获得超2个赞
this您的load函数内部指的是动态$('<img/>')元素。也是如此$(this).attr('id'),undefined并且没有一个装载机消失。
您需要在之前存储一个引用并使用它,如下所示:
$(document).ready(function() {
$('.img').each(function() {
let img = $(this).css('background-image').replace('url(', '').replace(')', '').replace(/\"/gi, "");
let id = $(this).attr('id')
$('<img/>').attr('src', img).on('load', function() {
$('#' + id + ' .image-loader').hide();
});
});
});
body {
margin: 0
}
.view {
height: 100vh;
width: 100vw;
background-color: blanchedalmond;
display: grid;
place-content: center;
}
.img {
background-position: center center;
background-size: cover;
height: 50vh;
width: 50vw;
}
#img1 {
background-image: url('https://eoimages.gsfc.nasa.gov/images/imagerecords/73000/73751/world.topo.bathy.200407.3x5400x2700.jpg');
}
#img2 {
background-image: url('https://edmullen.net/test/rc.jpg');
}
.image-loader {
height: 100%;
width: 100%;
display: grid;
justify-content: center;
align-items: center;
background-color: rgba(0, 0, 0, 0.7);
}
.cssload-speeding-wheel {
width: 49px;
height: 49px;
margin: 0 auto;
border: 5px solid rgba(255, 255, 255, 0.85);
border-radius: 50%;
border-left-color: transparent;
border-right-color: transparent;
animation: cssload-spin 800ms infinite linear;
-o-animation: cssload-spin 800ms infinite linear;
-ms-animation: cssload-spin 800ms infinite linear;
-webkit-animation: cssload-spin 800ms infinite linear;
-moz-animation: cssload-spin 800ms infinite linear;
}
@keyframes cssload-spin {
100% {
transform: rotate(360deg);
transform: rotate(360deg);
}
}
@-o-keyframes cssload-spin {
100% {
-o-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@-ms-keyframes cssload-spin {
100% {
-ms-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@-webkit-keyframes cssload-spin {
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@-moz-keyframes cssload-spin {
100% {
-moz-transform: rotate(360deg);
transform: rotate(360deg);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="view">
<div class="img" id="img1">
<div class="image-loader">
<div class="cssload-speeding-wheel"></div>
</div>
</div>
<div class="img" id="img2">
<div class="image-loader">
<div class="cssload-speeding-wheel"></div>
</div>
</div>
</div>
添加回答
举报