我有一组按钮,按下时应该改变颜色。 我用 getelementybyclassname 尝试过,但是当我按下不同的按钮时,所有按钮的颜色都会改变。我的目标是制作某种选择器,您可以在其中选择您的标准,并根据标准显示最终结果
function changecolor(){
var elements = document.getElementsByClassName("button")[0].style.color="blue";
}
<h2><span class="primary-text">Choose </span>your criteria</h2>
<button class="button"type="button" id="lightframe" onclick="changecolor()">easy to handle</button>
<button class="button"type="button" id="outdoor" onclick="changecolor()">small</button>
<button class="button"type="button" id="smallsize" onclick="changecolor">cheap</button>
最佳答案
你可以把按钮传给函数
function changecolor(button){
button.style.color = "blue";
}
<h2><span class="primary-text">Choose </span>your criteria</h2>
<button type="button" onclick="changecolor(this)">easy to handle</button>
<button type="button" onclick="changecolor(this)">small</button>
<button type="button" onclick="changecolor(this)">cheap</button>
或者像这样
function changecolor(){
this.style.color = "blue";
}
<h2><span class="primary-text">Choose </span>your criteria</h2>
<button type="button" onclick="changecolor.apply(this)">easy to handle</button>
<button type="button" onclick="changecolor.apply(this)">small</button>
<button type="button" onclick="changecolor.apply(this)">cheap</button>
编辑:
如果您想触发按钮的颜色,我强烈建议您使用 css 而不是在样式属性上进行操作。 jQuery 对此非常方便
$(".button").on("click", function () {
if($(this).hasClass("active")) {
$(this).removeClass("active");
}
else {
$(this).addClass("active");
}
});
.active {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2><span class="primary-text">Choose </span>your criteria</h2>
<button type="button" class="button">easy to handle</button>
<button type="button" class="button">small</button>
<button type="button" class="button">cheap</button>
关于javascript - 改变多个按钮的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50748008/