我有一個圖像標籤,我想在桌面和移動設備上顯示不同的圖像。會在每次調整大小時加載圖像嗎?
我有這樣解決了它:
JS:
function displayResponsiveImage() {
var largeImage = $('.responsive-image img.desktop');
var smallImage = $('.responsive-image img.mobile');
var realImage = $('.responsive-image img.real');
var largeImageSrc = largeImage.data('imagesrc');
var smallImageSrc = smallImage.data('imagesrc');
var viewportWidth = window.innerWidth;
if (viewportWidth > 480) {
realImage.attr('src', largeImageSrc);
} else {
realImage.attr('src', smallImageSrc);
}
realImage.show();
largeImage.hide();
smallImage.hide();
};
$(window).on('resize', function() {
displayResponsiveImage();
});
HTML:
<div class="image-container responsive-image" style="">
<a href="@Url.ContentUrl(Model.Link)">
<img class="desktop" data-imagesrc="@Html.GetUrl(Model.Image, true)" />
<img class="mobile" data-imagesrc="@Html.GetUrl(Model.MobileImage, true)" />
<img class="real" title="@Model.AltText" alt="@Model.AltText" />
</a>
</div>
我的問題是:這個設置,將在每個圖像重裝調整或者它只會在圖像更改src時重新加載?換句話說,我需要進一步優化嗎?
它不會因爲所有的圖像一旦加載DOM就會被加載,因爲它們都在HTML中。 – Roberrrt
但他們沒有來源..? – Winter
如果不使用JavaScript,它會不會成爲您的替代選擇?只需通過HTML和CSS? –