[英]Changing viewBox of an svg in javaScript
我正在尝试使用 JS 更改我的viewBox
,但没有成功
var mySVG = document.getElementById('svg');
if ($(window).width() >960) {
mySVG.setAttribute("viewBox", "400 400 400 400");
}
设置属性有效:) 所以可能不工作条件语句
var mySVG = document.getElementById('svg'); mySVG.setAttribute("viewBox", "0 0 200 200"); function changeViewBox(viewBox){ mySVG.setAttribute("viewBox", viewBox); }
<button onclick='changeViewBox("0 0 300 300")'>0 0 300 300</button> <button onclick='changeViewBox("0 0 400 400")'>0 0 400 400</button> <button onclick='changeViewBox("0 0 500 500")'>0 0 500 500</button> <svg id="svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 120"><style>.st0{fill:#bcbbbb}.st1{fill:#f48023}</style><path class="st0" d="M84.4 93.8V70.6h7.7v30.9H22.6V70.6h7.7v23.2z"/><path class="st1" d="M38.8 68.4l37.8 7.9 1.6-7.6-37.8-7.9-1.6 7.6zm5-18l35 16.3 3.2-7-35-16.4-3.2 7.1zm9.7-17.2l29.7 24.7 4.9-5.9-29.7-24.7-4.9 5.9zm19.2-18.3l-6.2 4.6 23 31 6.2-4.6-23-31zM38 86h38.6v-7.7H38V86z"/></svg>
如果您在 SVG 中使用 ID,则您的代码在更改属性时工作得很好:
function setViewBox() { var mySVG = document.getElementById('svg'); //if ($(window).width() >960) { // <-- disabled so we can test it here mySVG.setAttribute("viewBox", "400 400 400 400"); //} }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <svg id="svg" viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg" width="100px" height="100px"> <rect x="0" y="0" width="100%" height="100%" fill="#000"/> </svg> <button onClick="setViewBox()">set viewBox</button>
我减少了您设置的屏幕尺寸边界,以便在此处进行测试:
function setViewBox() { var mySVG = document.getElementById('svg'); if ($(window).width()>100) { // <-- reduced the size so you can test it mySVG.setAttribute("viewBox", "400 400 400 400"); } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <svg id="svg" viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg" width="100px" height="100px"> <rect x="0" y="0" width="100%" height="100%" fill="#000"/> </svg> <button onClick="setViewBox()">set viewBox</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.