You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS Safari中SVG图片naturalWidth返回window.innerWidth的问题求助

iOS Safari下SVG图片naturalWidth异常返回窗口宽度的问题

问题详情

  • 实际尺寸为92×21的SVG,代码中定义的width="28"、height="106",viewBox为0 0 28 106:
<svg width="28" height="106" viewBox="0 0 28 106" fill="none" xmlns="http://www.w3.org/2000/svg">
  • 通过img标签引入,借助onload事件读取naturalWidth赋值给iconWidth,再设置图片宽度:
<img
  src={widget.src.image}
  style={`width: ${iconWidth}px !important;`}
  onload={onImageLoad}
/>
  • 多数场景显示正常,但在iOS Safari(iPhone7 iOS15.4、iPhone11 iOS15.5)中调整页面尺寸后,naturalWidth偶尔会返回window.innerWidth的值,导致图片宽度与窗口一致,该Bug难以稳定复现。

解决方案

1. 修正SVG的尺寸定义

将SVG代码中的width和height改为实际的92和21,同时添加preserveAspectRatio确保缩放时比例正确,避免浏览器自动拉伸:

<svg width="92" height="21" viewBox="0 0 28 106" fill="none" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid meet">

2. 直接使用已知的SVG原始尺寸

既然明确SVG的实际宽度是92px,无需依赖naturalWidth,直接硬编码宽度即可:

const iconWidth = 92;
<img
  src={widget.src.image}
  style={`width: ${iconWidth}px !important;`}
/>

3. 给onload事件增加异常值校验

在onImageLoad中判断,如果naturalWidth接近窗口宽度,就使用预设的正确宽度:

function onImageLoad(e) {
  let width = e.target.naturalWidth;
  // 判定是否为异常值,可根据实际情况调整阈值
  if (Math.abs(width - window.innerWidth) < 10) {
    width = 92;
  }
  iconWidth = width;
  // 这里执行视图更新逻辑
}

4. 改用object标签加载SVG

object标签对SVG的尺寸解析更稳定,能规避img标签在iOS Safari下的这类异常:

<object
  data={widget.src.image}
  style="width: 92px;"
  type="image/svg+xml"
></object>

内容的提问来源于stack exchange,提问作者vld0s

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 23:31:03