根据图片自身大小自适应显示

本文介绍了如何使用 Vue.js 中的 imgHook.js 文件实现图片的1:1比例自适应,并创建ref来处理多个图片。通过getSize函数,根据屏幕大小动态计算图片宽度和高度,同时在窗口大小改变时进行实时更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建imghook.js:

//首先图片是1:1比例,解决不同图片免去单独设置宽高
// 在函数里创建ref,可以避免多张图片使用造成取值的问题
import { ref } from "vue"
// 使用解构视图是不会重新渲染的
const getSize = (naturalWidth, naturalHeight,imgWidth,imgHeight,imgStyle) => {
  const clientWidth = document.documentElement.clientWidth
  const fontSize = clientWidth / 750
  imgWidth.value = naturalWidth * fontSize + "px"
  imgHeight.value = naturalHeight * fontSize + "px"
  imgStyle.value = { width: imgWidth.value, height: imgHeight.value }
}
export const imgHook = (e) => {
  let imgStyle = ref({})
  const imgWidth = ref("")
  const imgHeight = ref("")
  const { naturalWidth, naturalHeight } = e	// 可以直接从dom对象拿这两个属性
  getSize(naturalWidth, naturalHeight,imgWidth,imgHeight,imgStyle)
  imgStyle.value = { width: imgWidth.value, height: imgHeight.value }
  // 监听屏幕变化事件重新加载 可不用,浏览器测试时候频繁切换屏幕就加了。。。。。。
  window.addEventListener("resize", () => {
    getSize(naturalWidth, naturalHeight,imgWidth,imgHeight,imgStyle)
  })
  return imgStyle
}

index.html:

 <img ref="prizeImgRef" class="img" :style="imgStyle.value" @load="imgLoad($event)" src="../assets/k2.png" alt="" srcset="">
import {imgHook} from '@/hooks/imgHook.js'  // 使用hook值得时候不要.value。会丢失响应式

let imgStyle = ref({})
let prizeImgRef = ref(null)
const imgLoad =(e)=> {
// dom对象传过去				
  imgStyle.value=imgHook(prizeImgRef.value)
}

demo文件地址https://github.com/cc147151/luck

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值