How do I click on the background to change blue to red and red to blue? What's wrong with my code? Help, thank you
##</body>
<script>
function te(){
var a = document.getElementById('test1');
if(a.id == 'test1'){
a.id = 'test2';
}else
a.id = 'test1';
}
</script>
</html>
<!DOCTYPE?html> <html> <head> </head> <style> #test1?{ width:300px; height:300px; background-color:blue; } </style> <body> <div?id="test1"></div> </body> <script> ????function?test1()?{ ????????var?a?=?document.getElementById('test1'); var?finalStyle?=?a.currentStyle???a.currentStyle?:?document.defaultView.getComputedStyle(a,?null);/*利用判斷是否支持currentStyle(是否為ie) 13?????來通過不同方法獲取style*/ if(finalStyle.backgroundColor=="rgb(0,?0,?255)"){ a.style.backgroundColor="red";? } else?if(finalStyle.backgroundColor=="rgb(255,?0,?0)"){ a.style.backgroundColor="blue";? } ??????} ?? function?addEvent(obj,type,handle){ ????try{??//?Chrome、FireFox、Opera、Safari、IE9.0及其以上版本 ????????obj.addEventListener(type,handle,false); ????}catch(e){ ????????try{??//?IE8.0及其以下版本 ????????????obj.attachEvent('on'?+?type,handle); ????????}catch(e){??//?早期瀏覽器 ????????????obj['on'?+?type]?=?handle; ????????} ????} } ?window.onload?=?function(){ ????????var?element?=?document.getElementById("test1"); ????????addEvent(element,"click",test1); ??????} </script> </html>
#test1?{ width:300px; height:300px;
You can use addinventlisner() to listen for click events, initialize it to red, change it to blue when you click it for the first time, and then turn it to red when you click it again
A is undefined when executed for the second time. Just put var a = document.getElementById('test1'); outside the function
Shouldn’t just change one ID, if the match is successful, another one will be displayed