我正在尝试使用JS更改我的viewBox
,但没有成功
var mySVG = document.getElementById('svg');
if ($(window).width() >960) {
mySVG.setAttribute("viewBox", "400 400 400 400");
}
发布于 2020-12-26 07:41:34
Set attribute works:)所以可能不能使用条件语句
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>
发布于 2020-12-26 07:39:03
如果您在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>
https://stackoverflow.com/questions/65452541
复制相似问题