1、通過js創建<image?>標簽來獲取背景圖片的寬高比;
2、當元素的高度大于原有比例計算出來的高度時,背景圖片的高度拉伸自適應100%,否則高度為auto,會自動被裁減
3、背景圖片容器高度變化時,自動計算背景圖片的高度
在這里插入圖片描述
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)
案例講解
1、初始化時的默認寬高;
2、背景圖片的寬高;
3、執行上面的代碼,并執行imgBox.setAttribute(‘style’, ‘height: 380px’),此時高度小于圖片的寬高比計算出來的高度,圖片高度被裁減;
4、執行imgBox.setAttribute(‘style’, ‘height: 580px’),此時高度大于圖片的寬高比計算出來的高度,圖片高度被拉伸100%;
5、當執行imgBox.setAttribute(‘style’, ‘height: 480px’),此時高度等于圖片的寬高比計算出來的高度,圖片高度正常展示;