我有3個屬性爲我的圖像是data-web-src
,data-tablet-src
和data-mobil-src
,我使用theese屬性作爲響應。如果我的圖像沒有data-mobile-src屬性而不是在移動設備或平板電腦上或web上移除此圖像。它的工作,但正如你看到下面的例子..我只是想在.slider
圖像這樣做,我怎麼能做到這一點?如何根據條件去除元素?
function noLazyImages(e) {
$(e + '.lazy_res').attr('src', function(_, oldSrc) {
var elData = $(this).data(),
winWidth = $(window).width();
if (winWidth < 768 && winWidth >= 480) {
if (elData['tabletSrc']) {
return elData['tabletSrc'];
}
} else if (winWidth < 480) {
if (elData['mobilSrc']) {
return elData['mobilSrc'];
}
}
return elData['webSrc'];
});
}
$(window).resize(function() {
noLazyImages("body img");
});
noLazyImages("body img");
img {
width: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<img class="lazy_res" data-web-src="https://image.prntscr.com/image/0d2af672b40c4d9ebf113a1784c33a7f.png" data-mobil-src="https://image.prntscr.com/image/b1e10f433e404191bb78123f5188dc56.png" data-tablet-src="https://image.prntscr.com/image/a9fb88455946432890b27a946e99d387.png"/>
<img class="lazy_res" data-web-src="https://image.prntscr.com/image/0d2af672b40c4d9ebf113a1784c33a7f.png" data-tablet-src="https://image.prntscr.com/image/a9fb88455946432890b27a946e99d387.png"/>
<div class="slider">
<div class="item">
<a href="#"><img class="lazy_res" data-web-src="https://image.prntscr.com/image/0d2af672b40c4d9ebf113a1784c33a7f.png" data-mobil-src="https://image.prntscr.com/image/b1e10f433e404191bb78123f5188dc56.png" data-tablet-src="https://image.prntscr.com/image/a9fb88455946432890b27a946e99d387.png"/>
</a>
</div>
<div class="item">
<a href="#"><img class="lazy_res" data-web-src="https://image.prntscr.com/image/0d2af672b40c4d9ebf113a1784c33a7f.png" data-tablet-src="https://image.prntscr.com/image/a9fb88455946432890b27a946e99d387.png"/></a>
</div>
</div>
使用具有多個源元素的圖像元素。你不需要這樣重新發明輪子。 – zzzzBov
,但圖片元素不適用於舊瀏覽器:// –
使用可用的圖片填充填充。 – zzzzBov