SVG内嵌JavaScript在Markdown中作为图片导入时失效的解决办法
解决嵌入带URL参数的动态SVG不显示问题
问题根源
你的SVG脚本中使用location.href获取URL参数,但当SVG通过<embed>嵌入宿主页面时,location.href指向的是宿主页面的地址,而非SVG自身的URL,导致无法读取shape等参数,最终无法生成图形。同时SVG默认未设置基础尺寸,脚本未执行时元素尺寸为0,也会导致看不到内容。
解决方案
1. 修正SVG脚本的URL获取方式
将脚本中获取URL的逻辑改为从SVG文档自身读取,替换location.href为document.currentScript.ownerDocument.URL:
<svg version="1.1" xmlns="http://www.w3.org/2000/svg"> <script> const svgUrl = document.currentScript.ownerDocument.URL; const params = new URL(svgUrl).searchParams; const shape = params.get('shape'); const strokeWidth = Number(params.get('strokeWidth')) || 0; document.documentElement.style.width = document.documentElement.style.height = (strokeWidth + 100) + 'px'; if(shape === 'rect'){ const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); rect.setAttribute('style', ` height: 100px; width: 100px; fill: ${params.get('fill') || 'transparent'}; stroke: ${params.get('stroke') || 'black'}; stroke-width: ${strokeWidth || 5}px; `); document.documentElement.prepend(rect); } </script> </svg>
2. 用<object>标签替代<embed>
<object>标签对SVG脚本的执行环境支持更稳定,替换Markdown中的嵌入代码:
<object data="shapes.svg?shape=rect" type="image/svg+xml"></object>
3. 给SVG添加默认尺寸(可选)
在SVG标签中预先设置基础宽高,避免脚本未执行时元素无尺寸:
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="110" height="110"> <!-- 脚本内容不变 --> </svg>
内容的提问来源于stack exchange,提问作者Ashish Antil
相关产品推荐
相关产品推荐

