var imgBgs = $('.imgBg')
imgBgs.each(function (indx, el) {
$(el).css({
'background-image': 'url(' + $(el).find('img').attr('src') + ')'
})
});
// 防抖函数
function debounce(func, wait) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
// 换图函数
function changeImageForMobile() {
const _winw = window.innerWidth;
if (_winw < 1200) {
$('[data-m-pic]').each(function () {
const img = $(this).data('m-pic');
switch (this.nodeName) {
case 'IMG': {
$(this).attr({
src: img
});
break;
}
default: {
$(this).css({
'background-image': 'url(' + img + ')'
});
}
}
});
}
}
// 使用防抖优化resize事件
const debouncedChangeImage = debounce(changeImageForMobile, 100);
// 监听resize事件
window.addEventListener('resize', debouncedChangeImage);
// 页面加载时执行一次
changeImageForMobile();
console