簡體   English   中英

如何通過單擊來改變 svg 元素的顏色?

[英]How to change color of svg-element back and fourth by clicking?

我想制作一個 SVG 圓(一個太陽),通過點擊它從黃色變為灰色,然后再次點擊它(依此類推)變回黃色。 我以不同的方式能夠通過單擊一次使太陽改變顏色,但在第二次單擊時它不會變回。

為什么這不起作用? 我該怎么做?

對不起,如果我以錯誤的方式發表這篇文章,這是我在這里的第一篇文章。

 // Trying to make it as one function with if-else $(document).ready(function(){ $("#sun").click(function() { if ($(this).attr("fill") == "yellow") { $(this).css({ fill: "grey" }); $(this).css({ stroke: "grey" }); } else { $("#sun").css({ fill: "yellow" }); $("#sun").css({ stroke: "orange" }); } }); }); // Trying to have the two clicks in different functions $(document).ready(function(){ $("#sun").click(function() { if ($(this).attr("fill") == "yellow") { $(this).css({ fill: "grey" }); $(this).css({ stroke: "grey" }); } }); }); $(document).ready(function(){ $("#sun").click(function() { if ($(this).attr("fill") == "grey") { $("#sun").css({ fill: "yellow" }); $("#sun").css({ stroke: "orange" }); } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <svg width="300" height="200"> <circle id="sun" cx="220" cy="40" r="20" stroke="orange" stroke-width="4" fill="yellow" /> </svg>

 // Trying to make one function with if-else $(document).ready(function(){ $("#sun").click(function() { if ($(this).attr("fill") == "yellow") { $(this).attr("fill", "grey"); $(this).css({ stroke: "grey" }); } else { $("#sun").attr("fill", "yellow"); $("#sun").css({ stroke: "orange" }); } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <svg width="300" height="200"> <circle id="sun" cx="220" cy="40" r="20" stroke="orange" stroke-width="4" fill="yellow" /> </svg>

它不起作用,因為$(this).css更改了內聯樣式(在您的代碼段中使用檢查檢查 html)而不是使用$(this).attr來更改fill屬性(而不是樣式fill

你可以像這樣切換一個類:

 sun.addEventListener("click",()=>{sun.classList.toggle("night")})
 #sun{stroke:orange;fill:yellow;} #sun.night{stroke:black;fill:silver;}
 <svg width="300" height="200"> <circle id="sun" cx="220" cy="40" r="20" stroke-width="4" fill="yellow" /> </svg>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM