javascript - 怎么样让它点击两次后还原成原来的颜色?
本文介绍了javascript - 怎么样让它点击两次后还原成原来的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
现在的效果是三个红色的小div点击哪个就哪个就变成黄色 同时其它的div都变成红色 现在想完善一下 在上面这个基础上 点击哪个div两次 还让它还原成原来的颜色 这个效果怎么弄呢?
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
#head{width: 400px;height: 500px;background-color: blue;margin: 0 auto;}
#div1,#div2,#div3{width: 100px;height: 80px;background-color: red;}
</style>
<script type="text/javascript">
window.onload=function(){
var oDiv1=document.getElementById('head');
var oDiv=oDiv1.getElementsByTagName('div')
for(i=0;i<oDiv.length;i++){
oDiv[i].onclick=function(){
for(j=0;j<oDiv.length;j++){
oDiv[j].style.backgroundColor="red"
this.style.backgroundColor="yellow"
}
}
}
}
</script>
</head>
<body>
<div id="head">
<div id="div1"></div><br />
<div id="div2"></div><br />
<div id="div3"></div>
</div>
</body>
</html>
解决方案
测试完毕,来得晚了点。代码的关键解析在最下面。
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
#head{width: 400px;height: 500px;background-color: blue;margin: 0 auto;}
#div1,#div2,#div3{width: 100px;height: 80px;background-color: red;}
</style>
<script type="text/javascript">
window.onload = function(){
var oDiv1 = document.getElementById('head');
var oDiv = oDiv1.getElementsByTagName('div')
for(i = 0; i < oDiv.length; i++){
oDiv[i].onclick=function(){
for(j=0; j<oDiv.length; j++){
if (this.getAttribute("style") == "background-color: yellow;") {
this.style.backgroundColor = "red";
} else {
oDiv[j].style.backgroundColor = "red";
this.style.backgroundColor = "yellow";
}
}
}
}
}
</script>
</head>
<body>
<div id="head">
<div id="div1"></div><br />
<div id="div2"></div><br />
<div id="div3"></div>
</div>
</body>
</html>
重点在于这边,当自身被点中后,如果style是黄色,则改变自身,否则就按旧有逻辑走:
for(j=0; j<oDiv.length; j++){
if (this.getAttribute("style") == "background-color: yellow;") {
this.style.backgroundColor = "red";
} else {
oDiv[j].style.backgroundColor = "red";
this.style.backgroundColor = "yellow";
}
}
以及,代码格式希望注意一下,别让人读起来费劲,反正最后可以压缩。
这篇关于javascript - 怎么样让它点击两次后还原成原来的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文