所以我有一个非常简单的代码,在我运行它时没有给出任何错误,但是问题是,它没有执行应有的功能...
当我单击中间的div时,它应该会更改颜色...
我想念什么?似乎找不到任何错字...
var panel = document.getElementById('color_panel');
document.getElementById('color_panel').addEventListener("click", function() {
var mySwitch = document.getElementById('color_panel').style.background;
if (mySwitch == "#76FF03") {
document.getElementById('color_panel').style.background = "#039BE5";
} else {
document.getElementById('color_panel').style.background = "#76FF03";
}
});
<body style="background: #37474F; margin: 0;">
<div id="color_panel" style="background: #76FF03; margin:
auto; font-family: Century Gothic; font-size: 40px; color: #37474F;
width: 200px; height: 200px; padding: 20px; margin-top: 50%;
transform: translateY(-50%); text-align: center;">
Click me!<br>or Double Click?</div>
<button style="font-size: 10px;
width: 100px; height: 20px; margin-left: 50%;
transform: translateX(-50%); border: solid 2px;
border-color: #FBC02D; border-radius: 5px;
background: #E3F2FD;" id="button" onclick="transition()">
add transition!</button>
您需要进行一些基本的调试。添加一条console.log
语句以检查您要添加到语句中的值,if
并查看其实际含义。
浏览器正在对其进行规范化,因此mySwitch == "#76FF03"
永远不会正确。
var panel = document.getElementById('color_panel');
document.getElementById('color_panel').addEventListener("click", function() {
var mySwitch = document.getElementById('color_panel').style.background;
console.log(mySwitch);
if (mySwitch == "#76FF03") {
document.getElementById('color_panel').style.background = "#039BE5";
} else {
document.getElementById('color_panel').style.background = "#76FF03";
}
});
<body style="background: #37474F; margin: 0;">
<div id="color_panel" style="background: #76FF03; margin:
auto; font-family: Century Gothic; font-size: 40px; color: #37474F;
width: 200px; height: 200px; padding: 20px; margin-top: 50%;
transform: translateY(-50%); text-align: center;">
Click me!<br>or Double Click?</div>
<button style="font-size: 10px;
width: 100px; height: 20px; margin-left: 50%;
transform: translateX(-50%); border: solid 2px;
border-color: #FBC02D; border-radius: 5px;
background: #E3F2FD;" id="button" onclick="transition()">
add transition!</button>
通常,通过将所有样式放在单独的样式表中,然后调整元素所属的类,可以更好地解决此类问题。
var panel = document.getElementById('color_panel');
panel.addEventListener("click", function() {
panel.classList.toggle("other");
});
body {
background: #37474F;
margin: 0;
}
#color_panel {
background: #76FF03;
margin: auto;
font-family: Century Gothic;
font-size: 40px;
color: #37474F;
width: 200px;
height: 200px;
padding: 20px;
margin-top: 50%;
transform: translateY(-50%);
text-align: center;
}
#color_panel.other {
background: #039BE5;
}
#button {
font-size: 10px;
width: 100px;
height: 20px;
margin-left: 50%;
transform: translateX(-50%);
border: solid 2px;
border-color: #FBC02D;
border-radius: 5px;
background: #E3F2FD;
}
<div id="color_panel">
Click me!<br>or Double Click?
</div>
<button style="" id="button" onclick="transition()">
add transition!
</button>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句