JavaScript点击div来回切换两个颜色及两张图片切换的方法
点击div切换颜色的代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .test1{ width:100px; height: 100px; background-color: green; } </style> <script type="text/javascript"> function myFunction(){ var test1 = document.getElementById('test1'); if(test1.style.backgroundColor=='yellow'){ test1.style.backgroundColor='green'; }else{ test1.style.backgroundColor='yellow'; } } </script> </head> <body> <div class="test1" id="test1" alt="" onclick="myFunction()"> </div> </body> </html>
这里有一个疑问就是:如果js语句中颜色代码为十六进制则不显示效果。目前还没有解决这个问题 求大神指教QAQ
点击图片来回切换:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script type="text/javascript"> function toggle(){ var test1 = document.getElementById('test1'); if(test1.src.indexOf('on') >= 0){ test1.src="./images/off.png"; }else{ test1.src="./images/on.png"; } } </script> <img id="test1" src="./images/on.png" alt="" onclick="toggle()" /> </body> </html>
-Abai.