为什么我的 Javascript 在尝试切换类时不起作用?

问题描述 投票:0回答:1
javascript html css svg toggle
1个回答
0
投票

试试这个代码:

    var svgs = document.querySelectorAll('.ces-smiley');
    
    svgs.forEach(function(svg) {
      svg.addEventListener('click', function() {
        svgs.forEach(function(svg) {
          svg.classList.remove('selected');
        });
        
        this.classList.add('selected');
      });
    });
.ces-smiley {
  cursor: pointer;
  transition: stroke-width 0.3s, stroke 0.3s;
  opacity: 0.5;
}

.ces-smiley.selected {
  stroke-width: 2;
  stroke: red;
  opacity: 1;
}
  <div class="ces-smileys">
    <svg class="ces-smiley-zma ces-smiley" height="100" viewBox="0 0 100 100" width="100" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
      <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="green"></circle>
    </svg>

      <svg class="ces-smiley-mak ces-smiley" height="100" viewBox="0 0 100 100" width="100" xmlns="http://www.w3.org/2000/svg">
      <rect x="10" y="10" width="80" height="80" stroke="black" stroke-width="3" fill="blue"></rect>
    </svg>

      <svg class="ces-smiley-neu ces-smiley" height="100" viewBox="0 0 100 100" width="100" xmlns="http://www.w3.org/2000/svg">
      <polygon points="50,5 90,90 10,90" stroke="black" stroke-width="3" fill="yellow"></polygon>
    </svg>

      <svg class="ces-smiley-moe ces-smiley" height="100" viewBox="0 0 100 100" width="100" xmlns="http://www.w3.org/2000/svg">
      <ellipse cx="50" cy="50" rx="40" ry="20" stroke="black" stroke-width="3" fill="orange"></ellipse>
    </svg>

      <svg class="ces-smiley-zmo ces-smiley" height="100" viewBox="0 0 100 100" width="100" xmlns="http://www.w3.org/2000/svg">
      <line x1="10" y1="10" x2="90" y2="90" stroke="black" stroke-width="3"></line>
    </svg>
  </div>

© www.soinside.com 2019 - 2024. All rights reserved.