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>
***huihui2018-01-18 14:31:34
<!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>
有人@我2017-12-25 17:31:29
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
p~ang~胖2017-12-25 11:15:13
A is undefined when executed for the second time. Just put var a = document.getElementById('test1'); outside the function
dabour2017-12-14 11:58:19
Shouldn’t just change one ID, if the match is successful, another one will be displayed