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

SVG图片选择器问题:下拉切换Object加载SVG失效求助

解决SVG通过<object>元素动态加载的问题

你的代码核心问题是:<object>元素加载外部资源时,需要使用data属性而非src属性,这和<img>标签的用法存在差异。

修正后的代码

<select onchange="document.getElementById('head-to-head-left').data = this.value">
  <option selected disabled>Pick a flower...</option>
  <option value="/seasons/2022/drivers/max_verstappen/head-to-head-left.svg">Max Verstappen</option>
  <option value="/seasons/2022/drivers/hamilton/head-to-head-left.svg">Lewis Hamilton</option>
  <option value="/seasons/2022/drivers/leclerc/head-to-head-left.svg">Charles Leclerc</option>
</select>
<br>
<object id="head-to-head-left" style="border: .2vw solid white;" type="image/svg+xml" width="90%"></object><br>

额外注意事项

  • 验证SVG路径正确性:检查相对/绝对路径是否指向真实存在的文件,可通过浏览器开发者工具的网络面板查看请求是否成功返回200状态码。
  • 确认服务器MIME类型配置:确保服务器对SVG文件返回的Content-Type为image/svg+xml,若返回text/plain等错误类型,浏览器可能无法正确渲染SVG内容。
  • 若修改data后仍无响应,可尝试重新创建<object>元素强制刷新,示例代码如下:
function loadSvg(url) {
  const objParent = document.getElementById('head-to-head-left').parentNode;
  const oldObj = document.getElementById('head-to-head-left');
  const newObj = document.createElement('object');
  newObj.id = 'head-to-head-left';
  newObj.style = 'border: .2vw solid white;';
  newObj.type = 'image/svg+xml';
  newObj.width = '90%';
  newObj.data = url;
  objParent.replaceChild(newObj, oldObj);
}

将select的onchange事件改为onchange="loadSvg(this.value)"即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:15:44