使用 JavaScript 操作 SVG 视图框(无库)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10085123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Manipulate SVG viewbox with JavaScript (no libraries)
提问by Andrew Clear
I'm trying to alter an SVG elements viewbox in JavaScript. Basically, I'm drawing a binary search tree, and when it gets too wide, I want to alter the viewbox to zoom out so that the tree fits in the window. I'm currently using:
我正在尝试在 JavaScript 中更改 SVG 元素视图框。基本上,我正在绘制一个二叉搜索树,当它变得太宽时,我想改变视图框以缩小,以便树适合窗口。我目前正在使用:
if(SVGWidth>=1000){
var a = document.getElementById('svgArea');
a.setAttribute("viewbox","0 0 " + SVGWidth + " 300");
}
The HTML is:
HTML是:
<svg id="svgArea" xmlns="w3.org/2000/svg"; xmlns:xlink="w3.org/1999/xlink"; width="1000" height="300" viewBox="0 0 1000 300">
I've also tried using setAttributeNS('null',...) but that didn't seem to work either. One strange thing I've noticed is that when I alert(a) it gives [object SVGSVGElement] which seems strange. Any help is appreciated.
我也试过使用 setAttributeNS('null',...) 但这似乎也不起作用。我注意到的一件奇怪的事情是,当我 alert(a) 时,它给出了 [object SVGSVGElement] 这看起来很奇怪。任何帮助表示赞赏。
回答by Anthony
It would be good to see the context of the svg, but the following worked for me with a pure SVG document:
看到 svg 的上下文会很好,但以下内容对我来说是纯 SVG 文档:
shape = document.getElementsByTagName("svg")[0];
shape.setAttribute("viewBox", "-250 -250 500 750");
Maybe it's because viewBox
is case-sensitive?
也许是因为viewBox
区分大小写?
回答by LUISAO
You have an error in your code: "viewbox" is different than "viewBox"...B is in uppercase. Change the code to:
您的代码中有错误:“viewbox”与“viewBox”不同...B 是大写的。将代码更改为:
a.setAttribute("viewBox","0 0 " + SVGWidth + " 300");