首页 > 解决方案 > 如何使用 JavaScript 切换 SVG 圆圈

问题描述

我的 JavaScript 代码有问题。

单击按钮时,我想显示和隐藏两个 SVG 圆圈。

我检查控制台时似乎没有任何错误,但按钮似乎不起作用......

这是按钮的代码,我将按钮 id 设置为“strike_btn”,将 SVG 圆圈的 id 设置为“strike”

代码:

onload = function() {
  function changeStr() {
    var strike = document.getElementById('strike');
    if (strike.style.display === 'block') {
      strike.style.display = "none";
    }
  }
  var strbutton = document.getElementById('strike_btn');
  strbutton.addEventListener('click', changeStr);
}
<div class="container-fluid">
  <div class="row">
    <div class="col-lg-7 col-md-7 col-sm-12 col-xs-12">
      <button type="button" class="btn btn-link" id="strike_btn">Strike</button>
    </div>
    <div class="col-lg-5 col-md-5 col-sm-8 col-xs-8">
    </div>
  </div>
</div>
<div class="container-fluid">
  <div class="row">
    <div class="col-lg-7 col-md-7 col-sm-12 col-xs-12" id="abc">
      <svg width="100%" height="100%" viewBox="0 0 600 780">
        <rect width="100%" height="100%" style="fill: white; stroke-width: 3; stroke: black"></rect>
        <rect x="21.5%" y="24.03846154%" width="56.6666667%" height="51.92307692%" style="fill: white; stroke-width: 2; stroke: black"></rect>
        <circle cx="-26.383257142857147%" cy="75.28764912669683%" r="4" fill="#1C6FA6"></circle>
        <circle cx="-28.12094285714285%" cy="52.508967516968326%" id ="strike" r="4" fill="#1C6FA6"></circle>
      </svg>
    </div>
  </div>
</div>

标签: javascriptonclick

解决方案


您需要添加一个style带有块的属性style="display: block;"才能使其工作(更改了片段的 x 坐标,因为圆圈超​​出了窗口范围)

window.onload = function() {
  function changeStr() {
    var strike = document.getElementById('strike');
    if (strike.style.display === 'block') {
      strike.style.display = "none";
    }
  }
  var strbutton = document.getElementById('strike_btn');
  strbutton.addEventListener('click', changeStr);
};
<div class="container-fluid">
  <div class="row">
    <div class="col-lg-7 col-md-7 col-sm-12 col-xs-12">
      <button type="button" class="btn btn-link" id="strike_btn">Strike</button>
    </div>
    <div class="col-lg-5 col-md-5 col-sm-8 col-xs-8">
    </div>
  </div>
</div>
<div class="container-fluid">
  <div class="row">
    <div class="col-lg-7 col-md-7 col-sm-12 col-xs-12" id="abc">
      <svg width="100%" height="100%" viewBox="0 0 600 780">
        <rect width="100%" height="100%" style="fill: white; stroke-width: 3; stroke: black"></rect>
        <rect x="21.5%" y="24.03846154%" width="56.6666667%" height="51.92307692%" style="fill: white; stroke-width: 2; stroke: black"></rect>
        <circle cx="26.383257142857147%" cy="75.28764912669683%" r="4" fill="#1C6FA6"></circle>
        <circle cx="28.12094285714285%" cy="52.508967516968326%" id ="strike" r="4" fill="#1C6FA6" style="display: block;"></circle>
      </svg>
    </div>
  </div>
</div>


推荐阅读