我需要在 iframe 中渲染一些 SVG,我需要使用 srcdoc 属性来完成。出于某种原因,我这样做的方式导致 SVG 的某些属性无法正确显示。
在下面的屏幕截图中,iframe 中的代码是相同的。
这里是重现这个的代码:
<svg height="150" width="300">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
</linearGradient>
</defs>
<ellipse cx="100" cy="70" rx="85" ry="55" fill="url(#grad1)" />
</svg>
<br><br>
<iframe width="300" height="150" srcdoc='<svg height="150" width="300">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
</linearGradient>
</defs>
<ellipse cx="100" cy="70" rx="85" ry="55" fill="url(#grad1)" />
</svg>'></iframe>
看起来它与 linearGradients 或 url 以及它们在这种情况下的行为方式有关。
我最近遇到了 iframe 和 srcdocs 的一些其他问题,我将其发布到 SO 上,并得到了很好的回应:iframes rendering mysteriously differently from regular web pages? -- 这有助于解决很多不一致问题,但似乎与这一问题无关。
我正在使用 Chrome/Webkit。
最佳答案
这似乎是 iframe srcdoc
的一个不幸结果文档解析内部目标链接。
使用 srcdoc
创建的文档are supposed to be given特殊基础 URL about:srcdoc
.
但是,在该文档中,the base URL for resolving external links or stylesheets is the parent document's URL .这可能意味着应该在父 DOM 而不是本地 DOM 中解析 ID。但这显然没有发生,因为在您的原始示例中,父文档中有一个带有该 ID 的有效渐变。现在,这可能是跨源限制阻止来自单独文档的资源的结果,但我没有在控制台上收到相应的错误。
当您开始将目标片段用于其他事情时,事情变得非常不稳定(并且跨浏览器不一致)。
In this fiddle ,转载为下面的片段,我使用目标片段来
从两个文档中引用渐变(一个用于描边,一个用于填充;在 Chrome (v38) 或 Firefox (v33) 中都不太幸运(IE 根本不支持 srcdoc)。
重复使用两个文档中的元素;都不是
<use>
在 FF 中呈现,Chrome 呈现本地椭圆重用,表明在这种情况下它根据本地文档解析片段。定义超链接的目的地。在这种情况下,FF 给我一个 POST 错误,但 Chrome 成功导航到目标父文档(请注意应用了
:target
样式)。当然,这仅在父文档具有可导航 URL(即保存的 JS Fiddle,但不是堆栈片段)时才有效。
所有这些都是说,这绝对是规范中的歧义和实现中的不一致,我建议寻找替代方案,例如使用数据 URI 作为 src
的 iframe。请注意,这在 IE 中仍然不起作用(它不支持 iframe 的数据 URI),并且您需要对任何 #
进行 URL 编码。和 %
文档中的字符。
iframe srcdoc
和 URL 片段测试用例
ellipse:target {
stroke:red;
}
<svg height="150" width="300">
<defs>
<linearGradient id="grad1" >
<stop offset="0" style="stop-color:rgb(255,255,0);stop-opacity:1" />
<stop offset="1" style="stop-color:rgb(255,0,0);stop-opacity:1" />
</linearGradient>
</defs>
<ellipse id="parentEllipse" cx="100" cy="70" rx="85" ry="55" fill="url(#grad1)" />
</svg>
<br><br>
<iframe width="300" height="150" srcdoc='<svg height="150" width="300">
<defs>
<linearGradient id="grad2" >
<stop offset="0" style="stop-color:rgb(255,255,0);stop-opacity:1" />
<stop offset="1" style="stop-color:rgb(255,0,0);stop-opacity:1" />
</linearGradient>
</defs>
<a xlink:href="#parentEllipse">
<ellipse id="ellipse" cx="100" cy="70" rx="85" ry="55" fill="url(#grad1) blue" stroke="url(#grad2) green" stroke-width="10px" /></a>
<use xlink:href="#ellipse" y="50"/>
<use xlink:href="#parentEllipse" x="50" />
</svg>'></iframe>
关于html - iframe 中的 SVG 存在奇怪的不一致问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26694141/