如何解决如何通过单击更改svg元素的颜色?
我想通过单击将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并检查了html),而是使用$(this).attr
更改了fill
属性(不是样式{ {1}})
您可以像这样切换课程:
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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。