SVG单击并切换

时间:2018-08-12 01:46:32

标签: javascript html svg


<svg>
  <a id="T" class="toggle" xlink:href="#0">
  <circle cx="238.1" cy="43.71" r="7.93" fill="#000" />
  </a>
  <a id="Y" class="toggle" xlink:href="#0">
  <circle cx="270.58" cy="119.2" r="6.93" fill="#000"/>
  </a>
  <a id="H" class="toggle" xlink:href="#0">
  <circle cx="203.7" cy="114.11" r="6.93" fill="#000"/>
  </a>

<div id="T_box" class="hide"><h1>........T.......</h1></div>
<div id="Y_box" class="hide"><h1>........Y........</h1></div>
enter code here

非常感谢@NewToJS

但这仍然无法切换....... 我需要显示A,但是单击B时A消失并显示B

Array.from(document.getElementsByClassName('toggle')).forEach(a => {
  a.addEventListener('click', function() {
document.getElementById(a.id + '_box').classList.toggle('hide');
  });});

.hide {display: none;}
div {background-color: rgba(0, 0, 0, .2);}

2 个答案:

答案 0 :(得分:1)

由于您已经在使用<a>,因此可以使用:target

h1 {
  display: none;
}
h1:target {
  display: block;
}
<svg>
      <a id="T" class="toggle" xlink:href="#T_box">
      	<circle cx="238.1" cy="43.71" r="7.93" fill="#000" />
      </a>
      <a id="Y" class="toggle" xlink:href="#Y_box">
      	<circle cx="270.58" cy="119.2" r="6.93" fill="#000"/>
      </a>
      <a id="H" class="toggle" xlink:href="#H_box">
      	<circle cx="203.7" cy="114.11" r="6.93" fill="#000"/>
      </a>
<svg>
<h1 id="T_box">A</h1>
<h1 id="Y_box">B</h1>
<h1 id="H_box">C</h1>

答案 1 :(得分:0)

因此,您尝试做的是一个简单的切换功能,您可以对其进行优化和清理,但最终它会隐藏所有人,并每次显示所需的内容。

Array.from(document.getElementsByClassName('toggle')).forEach(a => {
  a.addEventListener('click', function() {
		Array.from(document.getElementsByClassName('toggle')).forEach(i => {
			document.getElementById(i.id + '_box').classList.add('hide');
		});
    document.getElementById(a.id + '_box').classList.remove('hide');
  });
});
.hide {
  display: none;
}
<svg>
      <a id="T" class="toggle" xlink:href="#0">
      	<circle cx="238.1" cy="43.71" r="7.93" fill="#000" />
      </a>
      <a id="Y" class="toggle" xlink:href="#0">
      	<circle cx="270.58" cy="119.2" r="6.93" fill="#000"/>
      </a>
      <a id="H" class="toggle" xlink:href="#0">
      	<circle cx="203.7" cy="114.11" r="6.93" fill="#000"/>
      </a>
<svg>
<h1 id="T_box">A</h1>
<h1 id="Y_box" class="hide">B</h1>
<h1 id="H_box" class="hide">C</h1>

希望有帮助!