首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在javaScript中更改svg的viewBox

在javaScript中更改svg的viewBox
EN

Stack Overflow用户
提问于 2020-12-26 07:21:46
回答 2查看 116关注 0票数 1

我正在尝试使用JS更改我的viewBox,但没有成功

代码语言:javascript
运行
复制
var mySVG = document.getElementById('svg');
if ($(window).width() >960) {
   mySVG.setAttribute("viewBox", "400 400 400 400"); 
}
EN

回答 2

Stack Overflow用户

发布于 2020-12-26 07:41:34

Set attribute works:)所以可能不能使用条件语句

代码语言:javascript
运行
复制
var mySVG = document.getElementById('svg');

mySVG.setAttribute("viewBox", "0 0 200 200"); 

function changeViewBox(viewBox){ 
  mySVG.setAttribute("viewBox", viewBox); 
}
代码语言:javascript
运行
复制
<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>

票数 2
EN

Stack Overflow用户

发布于 2020-12-26 07:39:03

如果您在SVG中使用ID,那么在更改属性时,您的代码工作得很好:

代码语言:javascript
运行
复制
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"); 
  //}
}
代码语言:javascript
运行
复制
<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>

我减小了您设置的屏幕大小边界,以便在此处进行测试:

代码语言:javascript
运行
复制
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"); 
  }
}
代码语言:javascript
运行
复制
<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>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65452541

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档