自定义一个背景图片的高度,随着容器高度的变化而变化,小于图片的高度时裁剪,大于时拉伸100%展示
const setBackgroundImageHeight = (element) => { //todo 设置背景图片的高度
const getWidthNum = (width) => width ? width.slice(0, -2) : width; //todo 手动截掉宽度的px后缀
const img = new Image();
const { height, width, backgroundImage } = getComputedStyle(element); //? 获取到该元素的宽高
img.src = backgroundImage.replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
img.onload = function() {
var aspectRatio = img.width / img.height; //? 获取该背景图片的宽高比
const backgroundImageHeight = getWidthNum(height) > (getWidthNum(width)/aspectRatio) ? '100%' : 'auto'; //* 当元素的高度大于原有比例计算出来的高度时,背景图片的高度拉伸自适应100%
element.style.backgroundSize = `100% ${backgroundImageHeight}`;
console.log('%c ???? 张浩雨: img.onload -> element.style.backgroundSize ', 'font-size:16px;background-color:#ea00ea;color:white;', element.style.backgroundSize)
};
}
const imageHeightOnChange = (element) => { //todo 背景图片容器高度变化时,自动计算背景图片的高度
// 创建一个观察者对象
const observer = new MutationObserver((mutationsList, observe) => {
for(let mutation of mutationsList) {
if (mutation.attributeName === 'style') {
const style = mutation.target.getAttribute('style');
if (style.includes('height')) {
setBackgroundImageHeight(element)
}
}
}
});
// 传入目标节点和观察目标节点的属性变动
observer.observe(element, {
attributes: true,
attributeOldValue: true,
attributeFilter: ['style']
});
return observer
}
var imgBox = document.getElementById('img_box');
imageHeightOnChange(imgBox)