这是因为IE11无法处理图片元素。最后,由于我知道我们站点上的图片元素的所有断点(它们不会因为服务器端帮助程序而改变),所以我只添加了一点jquery,从图片标记中获取正确的源代码:
import $ from 'jquery';
import elementHelper from '../helpers/element-helper';
import throttle from 'lodash/throttle';
$(() => {
const $images = $('.object-fit');
const replacementClass = 'object-fit-replacement';
const $window = $(window);
if ($images.length) {
$images.each((index, item) => {
const $image = $(item);
let imageLoaded = false;
// this code will not run in IE if image is in the cache
$image.on('load', e => {
if (!imageLoaded) {
makeDiv(e.currentTarget);
imageLoaded = true;
}
});
// this code will run if image is already in the cache
if (item.complete && !imageLoaded) {
makeDiv(item);
imageLoaded = true;
}
});
}
$window.on('resize', throttle(() => {
$(`.${replacementClass}`).each((index, item) => {
const $picture = $(item).prev('picture');
console.log('resize', $picture.length)
if ($picture.length) {
$div.css('background-image', `url(${getPictureSource($picture)})`);
}
});
}, 100));
function makeDiv(image) {
const $image = $(image);
const $picture = $image.closest('picture');
let $div;
let $parent;
let imageSource;
if ($picture.length) {
$parent = $picture.parent();
imageSource = getImageSource($picture, $image);
} else {
$parent = $image.parent();
imageSource = image.src;
}
$div = $parent.find(`.${replacementClass}`);
if (!$div.length) {
$div = $(elementHelper.createElement('div', replacementClass));
$parent.append($div);
}
$div.css('background-image', `url(${imageSource})`);
$picture.hide();
$image.hide();
}
function getImageSource($picture, $image) {
const imageSource = $image.prop('currentSrc');
if (imageSource) {
return imageSource;
} else {
return getPictureSource($picture);
}
}
function getPictureSource($picture) {
// this assumes that the image helper has created the object fit picture tag and is using the standard 5 media queries
const $sources = $picture.children('source');
if ($sources.length === 5) {
const windowWidth = $window.outerWidth();
if (windowWidth < 380) {
return $sources.eq(0).attr('srcset');
} else if (windowWidth >= 380 && windowWidth < 767) {
return $sources.eq(1).attr('srcset');
} else if (windowWidth >= 767 && windowWidth < 1200) {
return $sources.eq(2).attr('srcset');
} else if (windowWidth >= 1200 && windowWidth < 1600) {
return $sources.eq(3).attr('srcset');
} else {
return $sources.eq(4).attr('srcset');
}
}
return $sources.last().attr('srcset'); // this assumes sources are done normally with desktop largest last (default to dektop)
}
});