vue中使用img标签的load事件使用踩坑(解决Safari中无法获取image宽高问题)

516 阅读1分钟

一般情况下在 vue 中处理 img 元素的 load 事件可使用下以下写法(Chrome中可用)

<template>
  <img src="demo.png" @load="onImageLoad">

</template>

<script setup>
const onImageLoad = (event) => {
  const width = event.path[0].width;
  const height = event.path[0].height;
}
</script>

Safari中以上写法不生效,需要使用以下写法(同时兼容 ChromeSafari

<template>
  <img src="demo.png" id="image">
</template>

<script setup>
   const image = document.getElementById("image");
   image.addEventListener("load", () => {
    // chrome 浏览器中获取宽高
    if (event.path) {
        const width = event.path[0].width;
        const height = event.path[0].height; 
   // safari 浏览器中获取宽高
   } else {
        const width = event.target.width;
        const height = event.target.height;
   }
}, false);