本文介绍了用javascript在两种颜色之间切换的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
JavaScript初学者在这里.我本质上是想进行简单的切换.如果元素为黑色,则将其更改为白色.如果是白色,请将其更改为黑色.
Javascript beginner here. I essentially want to make a simple switch. If an element is black, change it to white. If it is white, change it to black.
function changeClass() {
if (document.getElementById('myButton').style.backgroundColor == "white") {
document.getElementById('myButton').style.backgroundColor = "black";
} else {
document.getElementById('myButton').style.backgroundColor = "white";
}
}
<button class="normal" id="myButton" onclick='changeClass()' >Change Colour</button>
虽然此代码非常混乱.有一个更好的方法吗?
This code is quite messy though. Is there a better way to do this?
推荐答案
切换类:
function changeClass(){
document.getElementById('myButton').classList.toggle("the-class");
}
您的CSS所在的位置:
where your CSS is:
.the-class {
background-color: black;
}
...假设元素的正常背景颜色为白色.
...assuming the element's normal background color is white.
有关 classList
的更多信息此处.支持很好,但是在较旧的环境中可能需要使用polyfill.
More about classList
here. Support is good, but you may need a polyfill in older environments.
示例:
function changeClass() {
document.getElementById('myButton').classList.toggle("the-class");
}
.the-class {
background-color: black;
}
<button class="normal" id="myButton" onclick='changeClass()'>Change Colour</button>
这篇关于用javascript在两种颜色之间切换的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!