gpt4 book ai didi

javascript - 如何在连续单击时切换不同的颜色(在 SVG 对象上)

转载 作者:行者123 更新时间:2023-11-28 17:04:22 27 4
gpt4 key购买 nike

我试图让组中的所有元素在不同的点击次数下更改为特定颜色。单击一次 = 红色,单击两次 = 蓝色等。它需要切换组中的所有子项。

JavaScript

function call1() {
console.log('call1');
const children = document.getElementById('btn1').children;
$(document).ready(function(){
$("btn1").toggle(
function(){$("btn1").css({"fill": "red"});},
function(){$("btn1").css({"fill": "blue"});},
function(){$("btn1").css({"fill": "green"});
});
});
}

SVG 文件

<g id="btn1" onclick="call1()">
<polygon fill="#FF0013" points="366.699,131 410,56 453.301,131 "/>
<polygon fill="#07FF00" points="323.699,656 367,581 410.301,656 "/>
<polygon fill="#0000FF" points="409.699,656 453,581 496.301,656 "/>
<polygon points="366.699,581 410,656 453.301,581 "/>
</g>

我希望 SVG 组中的所有元素在第一次单击时将颜色更改为红色,第二次单击时更改为绿色,第三次单击时更改为蓝色。

最佳答案

您可以使用模数和 switch 语句来循环显示每种颜色:

var count = 0;

function call1() {
const button = $("#btn1");
console.log(count);
count = count % 3 + 1;
switch (count) {
case 1:
button.css("fill", "red");
break;
case 2:
button.css("fill", "blue");
break;
case 3:
button.css("fill", "green");
break;
}
}

示例:

var count = 0;

function call1() {
const children = $("#btn1").children();
count = count % 3 + 1;
switch (count) {
case 1:
children.css("fill", "red");
break;
case 2:
children.css("fill", "blue");
break;
case 3:
children.css("fill", "green");
break;
}
}
<svg height="1000" width="100%">
<g id="btn1" onclick="call1()">
<polygon fill="#FF0013" points="366.699,131 410,56 453.301,131 "/>
<polygon fill="#07FF00" points="323.699,656 367,581 410.301,656 "/>
<polygon fill="#0000FF" points="409.699,656 453,581 496.301,656 "/>
<polygon points="366.699,581 410,656 453.301,581 "/>
</g>
</svg>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

关于javascript - 如何在连续单击时切换不同的颜色(在 SVG 对象上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56270724/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com