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

1、通过js创建<image?>标签来获取背景图片的宽高比;

2、当元素的高度大于原有比例计算出来的高度时,背景图片的高度拉伸自适应100%,否则高度为auto,会自动被裁减

3、背景图片容器高度变化时,自动计算背景图片的高度

在这里插入图片描述

js 复制代码
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'),此时高度等于图片的宽高比计算出来的高度,图片高度正常展示;

相关推荐
@atweiwei7 小时前
LangChainRust 0.33.0 发布:让 Agent 应用更容易运行、观察和评测
服务器·前端·javascript
qq_2744751512 小时前
第 28 篇:Promise 全解析:状态、then/catch/finally、静态方法 all/race/allSettled/any
开发语言·javascript
GuWenyue14 小时前
昵称限 20 字,8 个 emoji 却超长:一个「字」在系统里有四种长度
javascript·数据库·后端
画中有画17 小时前
自动化脚本中使用RSA
前端·javascript·自动化
只睡四小时19 小时前
AI 写的倒计时:Electron 每轮吞 0.8 秒
javascript·人工智能·性能优化·electron·时间管理·番茄钟
全速向光19 小时前
用 Three.js 从零打造一棵会发光的 3D 圣诞树
开发语言·javascript·3d
布语world19 小时前
某东pc滑块分析
前端·javascript·网络·python·安全
zhanlang021719 小时前
CSS 初探:网页的 “美容师” 与三大引入方式 1.0
前端·css
zhoulcc20 小时前
为什么 uni-app 小程序里并排选项总变竖排?缺了 box-sizing 重置
前端·css·小程序·uni-app·box-sizing
map_vis_3d20 小时前
百度地图自定义覆盖物 CustomOverlay:用 HTML、React、Vue 组件做标注
前端·javascript·vue·react·百度地图