- <!DOCTYPE html>
- <html lang="cn">
- <head>
- <meta charset="UTF-8">
- <title>Document</title>
- <style>
- span{
- padding: 5px 10px;
- background-color:darkgreen;
- /* width: 20px; */
- /* height: 20px; */
- /* display: block; */
- }
- </style>
- <script type="text/javascript">
- window.onload = function() {
- var hlist = document.getElementsByTagName('span');
- //console.log(hlist.length)
- hlist[0].style.backgroundColor = "brown";
- for (var i = 0; i <hlist.length; i++) {
- var htag = hlist[i];
- htag.onclick = function() {
- //alert(this.innerHTML);
- setColor(hlist,this.innerHTML - 1);
- }
- }
- }
- setColor = function(hlist,index){
- for(var i = 0; i < hlist.length; i++){
- if(index != i){
- //hlist[i].setAttribute("class", "a");
- hlist[i].style.backgroundColor = "darkgreen";
- }else{
- //hlist[i].setAttribute("class", "b");
- hlist[i].style.backgroundColor = "brown";
- }
- }
- }
- </script>
- </head>
- <body>
- <span>1</span>
- <span>2</span>
- <span>3</span>
- <span>4</span>
- <span>5</span>
- <span>6</span>
- <span>7</span>
- <span>8</span>
- <span>9</span>
- </body>
- </html>
来源: http://www.bubuko.com/infodetail-2585303.html