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

14 篇文章 0 订阅

创建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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值