gpt4 book ai didi

JavaScript 单击按钮颜色

转载 作者:太空宇宙 更新时间:2023-11-04 14:59:45 26 4
gpt4 key购买 nike

我希望我的按钮在其中一个被单击时更改为某种颜色,然后在另一个被单击时又恢复为默认颜色。默认颜色是灰色,然后当单击一个按钮时,它将保持橙色直到单击另一个按钮。我不太确定如何实现这一目标。

使用 vanilla JS 是一个要求,所以我不能使用 jQuery

这是 HTML 和 JS:

<button type="button" id="button1">1</button>
<button type="button" id="button2">2</button>
<button type="button" id="button3">3</button>

...

var userRating

document.getElementById('button1').onclick = function () {
console.log(this.id + " was clicked")
userRating = 1;
}
document.getElementById('button2').onclick = function () {
console.log(this.id + " was clicked")
userRating = 2;
}
document.getElementById('button3').onclick = function () {
console.log(this.id + " was clicked")
userRating = 3;
}

这是 CSS:

button {
-moz-box-shadow: 0px 10px 14px -7px #AAAAAA;
-webkit-box-shadow: 0px 10px 14px -7px #AAAAAA;
box-shadow: 0px 10px 14px -7px #AAAAAA;
background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #AAAAAA), color-stop(1, #AAAAAA));
background:-moz-linear-gradient(top, #AAAAAA 5%, #AAAAAA 100%);
background:-webkit-linear-gradient(top, #AAAAAA 5%, #AAAAAA 100%);
background:-o-linear-gradient(top, #AAAAAA 5%, #AAAAAA 100%);
background:-ms-linear-gradient(top, #AAAAAA 5%, #AAAAAA 100%);
background:linear-gradient(to bottom, #AAAAAA 5%, #AAAAAA 100%);
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#AAAAAA', endColorstr='#AAAAAA',GradientType=0);
background-color:#77b55a;
-moz-border-radius:4px;
-webkit-border-radius:4px;
border-radius:4px;
border:1px solid #4b8f29;
display:inline-block;
cursor:pointer;
color:#ffffff;
font-family:Arial;
font-size:13px;
font-weight:bold;
padding:6px 12px;
text-decoration:none;
text-shadow:0px 1px 0px #5b8a3c;
}
button:hover {
background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #FF851B), color-stop(1, #FF851B));
background:-moz-linear-gradient(top, #FF851B 5%, #FF851B 100%);
background:-webkit-linear-gradient(top, #FF851B 5%, #FF851B 100%);
background:-o-linear-gradient(top, #FF851B 5%, #FF851B 100%);
background:-ms-linear-gradient(top, #FF851B 5%, #FF851B 100%);
background:linear-gradient(to bottom, #FF851B 5%, #FF851B 100%);
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#FF851B', endColorstr='#FF851B',GradientType=0);
background-color:#FF851B;
}
button:active {
position:relative;
top:1px;
}

如果您能为我指出正确的方向,那就太好了!我对这些东西很陌生。

最佳答案

一种可能的解决方案是为所选按钮添加一个 CSS 类:

button:hover, button.selected {
...
}

然后,像这样为按钮设置所选类:

document.getElementById('button1').className = 'selected';

您可以像这样清除所选的类:

document.getElementById('button1').className = '';

完整的解决方案在这里:https://jsfiddle.net/3fzb1kk1/

关于JavaScript 单击按钮颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35903188/

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