【问题标题】:How to hide SVG elements with JavaScript on a button click?如何在单击按钮时使用 JavaScript 隐藏 SVG 元素?
【发布时间】:2017-02-27 17:30:36
【问题描述】:

我已尝试使用此代码:

svgElement.style.display = "none";

但它没有工作。 getElementById 怎么可能做到这一点?

【问题讨论】:

  • 给你的 svgElement 一个唯一的 id 并调用那个 id?
  • 调用这个id的代码是什么?
  • document.getElementById("rect").what? = 什么?;
  • .style += "display:none;"

标签: javascript svg


【解决方案1】:

您可以使用样式属性display并将其设置为none

function hideSVG() {
  var style = document.getElementById("myRect").style.display;
  if(style === "none")
    document.getElementById("myRect").style.display = "block";
  else
    document.getElementById("myRect").style.display = "none";
  //or to hide the all svg
  //document.getElementById("mySvg").style.display = "none";
}
<svg id="mySvg">
  <rect id="myRect" fill="red" width="100px" height="100px"></rect>
</svg>
<button onclick="hideSVG()">Hide/Show</button>

【讨论】:

  • 谢谢!它对我有用。如何再次显示该项目?
  • 它只是隐藏。能否请您添加相同 ID 的显示代码。
  • 运行代码sn-p,你会看到Hide/Show按钮。单击它一次,它将隐藏矩形。再次点击它就会显示出来
  • 是的。看到了。我怎样才能为几个对象做到这一点?因为当我为其他对象分配相同的 ID 时,它不起作用,因为 ID 必须是唯一的,但我想同时为多个对象执行此操作。
  • 如果它们都在同一个 SVG 中,您可以使用 SVG id。或者对每个对象使用相同的类
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-31
  • 2011-11-03
  • 1970-01-01
相关资源
最近更新 更多