自定义一个背景图片的高度,随着容器高度的变化而变化,小于图片的高度时裁剪,大于时拉伸100%展示

发布于:2024-06-29 ⋅ 阅读:(12) ⋅ 点赞:(0)

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’),此时高度等于图片的宽高比计算出来的高度,图片高度正常展示;
在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到