如何在点击后将一个 svg 切换到另一个 svg?

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

您可以将路径保存为字典,并将

svg
传递到
myFunction
中,并根据
innerHTML
是否具有
element
类来更新
dark-mode

var lighting_mode_paths = {
  'moon': '<path d="M21.7519 15.0019C20.597 15.4839 19.3296 15.75 18 15.75C12.6152 15.75 8.25 11.3848 8.25 5.99999C8.25 4.67039 8.51614 3.40296 8.99806 2.24805C5.47566 3.71785 3 7.19481 3 11.25C3 16.6348 7.36522 21 12.75 21C16.8052 21 20.2821 18.5243 21.7519 15.0019Z" stroke="#000000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>',
  'sun': '<path d="M12 3V5.25M18.364 5.63604L16.773 7.22703M21 12H18.75M18.364 18.364L16.773 16.773M12 18.75V21M7.22703 16.773L5.63604 18.364M5.25 12H3M7.22703 7.22703L5.63604 5.63604M15.75 12C15.75 14.0711 14.0711 15.75 12 15.75C9.92893 15.75 8.25 14.0711 8.25 12C8.25 9.92893 9.92893 8.25 12 8.25C14.0711 8.25 15.75 9.92893 15.75 12Z" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>',
};

function myFunction(svg) {
  var element = document.body;
  element.classList.toggle("dark-mode");
  
  if (element.classList.contains('dark-mode')) {
    svg.innerHTML = lighting_mode_paths['moon'];
  } else {
    svg.innerHTML = lighting_mode_paths['sun'];
  }
}
.dark-mode {
  background: #333;
}

.dark-mode path {
  fill: #fff;
  stroke: #fff;
}
<svg onclick="myFunction(this)" width="24" height="24" viewBox="0 0 24 24" fill="#000" xmlns="http://www.w3.org/2000/svg">
    <path d="M12 3V5.25M18.364 5.63604L16.773 7.22703M21 12H18.75M18.364 18.364L16.773 16.773M12 18.75V21M7.22703 16.773L5.63604 18.364M5.25 12H3M7.22703 7.22703L5.63604 5.63604M15.75 12C15.75 14.0711 14.0711 15.75 12 15.75C9.92893 15.75 8.25 14.0711 8.25 12C8.25 9.92893 9.92893 8.25 12 8.25C14.0711 8.25 15.75 9.92893 15.75 12Z" stroke="#000" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
  </path>
</svg>

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