gpt4 book ai didi

javascript - 如何使按钮恢复到原来的颜色

转载 作者:行者123 更新时间:2023-12-02 18:39:28 24 4
gpt4 key购买 nike

我有以下代码,我试图弄清楚如果再次单击第一个按钮,如何将其设置为白色,下一个按钮也是如此。所以,如果我点击它一次,它就会变成红色,但如果我再次点击它,它就会变成白色。任何想法。

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> color divs </title>
<meta name="author" content="Lee Middleton" />
<meta name="keywords" content="CIS120/121/122" />
<meta name="description" content="Template for x/html, CSS and JavaScript" />
<style type="text/css">
.container {
border: 1px solid blue;
border-radius: 10px;
width: 100px;
height: 50px;
}
</style>
<script language="javascript">
function changeColor(whichOne)
{
var thatOne = eval(whichOne);
var element = document.getElementById(whichOne);
var color = "ff";
var stringColor;
if (whichOne == 1)
{
stringColor = "#" + color + "0000";
else {
alert('it was clicked') ;
}
}




}
else if (whichOne== 2)
{
stringColor = "#0000" + color;
}
element.style.backgroundColor = stringColor;
}
</script>

<body>
<div class='container' id='1' style='margin: 150px 0 0 75px; float: left;' onclick='changeColor(1);'></div>
<div class='container' id='2' style='margin: 150px 0 0 175px; float: left;' onclick='changeColor(2);'></div>
<div class='container' id='3' style='margin: 150px 0 0 220px; float: left;' onclick='changeColor(3);'></div>
</body>
</html>

最佳答案

正如另一个解决方案提到的,您可以将以前的颜色存储在变量中,以便在必要时重置它,但是如果您只想将元素返回到其默认颜色,则有一种更简单的方法。

就这样做:

element.style.backgroundColor = '';

这只是取消设置样式属性的背景颜色部分,允许使用 css 中的颜色。

因此,要在默认颜色和颜色之间切换,您可以执行以下操作:

element.style.backgroundColor = element.style.backgroundColor ? '' : '#' + color;

关于javascript - 如何使按钮恢复到原来的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16974654/

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