使用 JavaScript 操作 SVG viewbox(无库)
Manipulate SVG viewbox with JavaScript (no libraries)
我正在尝试在JavaScript中更改SVG元素视图框。基本上,我正在绘制一个二叉搜索树,当它变得太宽时,我想更改视图框以缩小,以便树适合窗口。我目前正在使用:
if(SVGWidth>=1000){
var a = document.getElementById('svgArea');
a.setAttribute("viewbox","0 0 " + SVGWidth + " 300");
}
该 HTML 是:
<svg id="svgArea" xmlns="w3.org/2000/svg"; xmlns:xlink="w3.org/1999/xlink"; width="1000" height="300" viewBox="0 0 1000 300">
我也尝试过使用 setAttributeNS('null',...),但这似乎也不起作用。我注意到的一件奇怪的事情是,当我发出警报(a)时,它会给出[对象SVGSVGElement],这似乎很奇怪。任何帮助,不胜感激。
很高兴看到 svg 的上下文,但以下内容对我使用纯 SVG 文档有用:
shape = document.getElementsByTagName("svg")[0];
shape.setAttribute("viewBox", "-250 -250 500 750");
也许是因为viewBox
区分大小写?
您的代码中有一个错误:"viewbox"与"viewBox"不同...B 为大写。将代码更改为:
a.setAttribute("viewBox","0 0 " + SVGWidth + " 300");
我有一个非常相似的用例,其中调整SVG的大小对于响应式设计至关重要。
const windowWidth = window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
const windowHeight = window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
// used getElementById for specific SVG
const shape = document.getElementById("background-svg");
function onWindowResize(){
console.log(windowWidth, windowHeight);
if (windowWidth < 600 || windowHeight < 900) {
shape.setAttribute("viewBox", "0 0 400 800");
}
// Added an Event Listener
window.addEventListener("resize", onWindowResize);
这种方法对我来说效果很好,我希望有改进的余地,很乐意找到替代解决方案。祝您编码愉快!
此外,如果要动态设置视图框维度,请使用 ES6 模板文本而不是字符串串联。
shape = document.getElementsByTagName("svg")[0];
const view = `${xValue} ${yValue} ${width} ${height}`; // template literals
shape.setAttribute("viewBox", view);
相关文章:
- 图片照片库
- 与其他库的jQuery.noConflict()
- Phonegap-(安卓/iphone)多个图像的图像库出现问题
- 同位素库错误:未捕获错误无布局模式包装生产线8
- 有没有一个javascript图形绘制库可以进行气球树布局
- 从信息框调用弹出图像库
- 任何方式使AJAX调用Gmail API,而无需通过JS库
- 使用递归、Ramda.js和无点样式重构字符串的getPermutations()
- 如何将我的javascript库公开给其他客户端使用
- 通过另一个php应用程序将我的项目推送到Github存储库中
- 将依赖外部库的UMD模块与browserfy捆绑在一起
- 照片滑动 - 无图库视图 - 没有导航按钮
- 使用 JavaScript 操作 SVG viewbox(无库)
- 如何在幻灯片中显示随机图库(无随机图像)
- 普通(无库)AJAX文件上传
- js库,用于支持拖放的有向无循环图
- 在Javascript中修改a:before样式的背景.(无库)
- Javascript - setInterval,如果选中复选框,则交替选中单选(无库)
- 在head中使用1jquery库在body中使用other无冲突不工作
- 如何只使用Javascript制作灯箱动画效果(无库)