我正在尝试显示缩放到对象大小的 SVG,以便缩放 600x600 的 svg 以适合 500x500 的对象或 300x300 的任何对象。 这一切在 FireFox 中都工作得很好,但 Safari 和 Chrome (Webkit) 只是裁剪 SVG
<div class="svg">
<object id="diagram" type="image/svg+xml" class="emb-diag" data="my.svg">
</object>
</div>
// Class method
setViewBox : function(objectSVG, containerSize, viewboxSize)
{
objectSVG.setAttribute("width", containerSize);
objectSVG.setAttribute("height", containerSize);
var svgDoc;
if ( typeof objectSVG.getSVGDocument != 'undefined')
{
svgDoc = objectSVG.getSVGDocument();
if (svgDoc == null)
{
svgDoc = objectSVG.contentDocument;
if (svgDoc == null)
{
return;
}
}
}
else
{
svgDoc = objectSVG.contentDocument;
if (svgDoc == null)
{
return;
}
}
var svgElem = svgDoc.documentElement;
if (svgElem)
{
svgElem.setAttribute("viewBox", "0 0 " + viewboxSize + " " + viewboxSize);
svgElem.setAttribute("preserveAspectRatio", "xMinYMin meet");
}
},
TheClass.setViewBox(document.getElementById("diagram"), 500, 600);
在 Safari 中调试此行时
var svgElem = svgDoc.documentElement;
像 Chrome 一样将 svgElem 变量解释为 HTMLHtmlElement
svgDoc: HTMLDocument
svgElem: **HTMLHtmlElement**
accessKey: ""
attributes: NamedNodeMap
baseURI: "about:blank"
childElementCount: 2
childNodes: NodeList[2]
children: HTMLCollection[2]
classList: DOMTokenList
className: ""
clientHeight: 500
clientLeft: 0
clientTop: 0
clientWidth: 500
contentEditable: "inherit"
dataset: DOMStringMap
dir: ""
...
Chrome 确实报告了以下内容
Resource interpreted as Document but transferred with MIME type image/svg+xml:
"file:///my.svg". jquery.min.js:2
(anonymous function) jquery.min.js:2
f.Callbacks.o jquery.min.js:2
f.Callbacks.p.fireWith jquery.min.js:2
e.extend.ready jquery.min.js:2
c.addEventListener.B
但我明白了 - 但为什么呢?我的谷歌搜索事件没有阐明此事。
FireFox 将其解释为: 作为正确的 SVG DOM,整个 SVG 文件可以按照您的预期进行扩展
先发制人,我已经沿着这条路线走下去了,更糟糕的是这两行都返回 null svgDoc = objectSVG.getSVGDocument(); svgDoc = objectSVG.contentDocument;
FireFox 没问题,Safari 和 Chrome 无法缩放
我可以使用缩放工作来做到这一点,但 svgDoc 保持为空,但无法访问 SVG DOM,这就是我想要的。
我还没有测试过 SVG 内联变体,但如果可能的话,我真的不想走这条路。
如果有人在我之前走过这条路,一路上在灌木丛中艰难前行,那么我们将非常感谢您的见解。
最佳答案
在 <object>
的 onload 事件发生之前,您不应该尝试访问 contentDocument元素已触发。尝试将 TheClass.setViewBox 调用移动到 onload 处理程序中,例如
<object onload="TheClass.setViewBox..."
关于javascript - 通过 Javascript 访问 Chrome 和 Safari 中的 SVG DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12884236/