標籤:ext object 沒有 mouse div 迴圈 tag list dcl
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> body,ul{margin: 0;padding: 0;} ul{ width:500px; margin:100px auto ; padding: 10px; border: solid 1px #E3E3E3; list-style:none; line-height: 2; } li{ padding: 8px 10px; border-radius: 8px; } /* li:nth-child(odd){ background: #E7E7E7; } li:nth-child(even){ background: #EEE8AA; } li:hover{ background: red; color: white; }*/ .bg1{ background: #E3E3E3; } .bg2{ background: #EEE8AA; } .bg3{ color: white; background: red; } </style> </head> <body> <ul class="news"> <li>疑似作弊者對手:沒手機他像換個人 下得又慢又差</li> <li>九冠王隊重慶新姿態戰圍甲 古力:希望不拖隊友後腿</li> <li>拜仁全隊賽前誓師!封死C羅 幹掉皇馬進決賽!</li> <li>在本賽季歐洲金靴的競爭中,梅西還沒有坐穩優勢…</li> <li>疑似作弊者對手:沒手機他像換個人 下得又慢又差</li> <li>九冠王隊重慶新姿態戰圍甲 古力:希望不拖隊友後腿</li> <li>拜仁全隊賽前誓師!封死C羅 幹掉皇馬進決賽!</li> <li>在本賽季歐洲金靴的競爭中,梅西還沒有坐穩優勢…</li> <li>疑似作弊者對手:沒手機他像換個人 下得又慢又差</li> <li>九冠王隊重慶新姿態戰圍甲 古力:希望不拖隊友後腿</li> <li>拜仁全隊賽前誓師!封死C羅 幹掉皇馬進決賽!</li> <li>在本賽季歐洲金靴的競爭中,梅西還沒有坐穩優勢…</li> </ul> </body> <script type="text/javascript"> //通過類名得到的是一個類數組,資料類型是object;它也有自己對應的索引值,索引從0開始 var news = document.getElementsByClassName(‘news‘)[0]; //給news元素建立了一個屬性mAtt並賦值mValue //1.setAttribute("屬性名稱","屬性值") 設定屬性 getAttribute("屬性名稱")// news.setAttribute("mAtt","mValue");// console.log(news.getAttribute("mAtt")); //2. html自訂屬性 標籤元素.屬性 = "屬性值";// news.att = "value";// console.log(news.att) //通過標籤名來擷取標籤元素,得到類數組 var lis = news.getElementsByTagName(‘li‘); console.log(typeof lis); //遍曆lis for (var i = 0; i < lis.length; i++) { if(i % 2 == 1){ lis[i].className = "bg1"; //自訂一個屬性來暫時儲存當前className的值// lis[i].oldClassName = "bg1"; }else{ lis[i].className = "bg2";// lis[i].oldClassName = "bg2"; } //滑鼠事件 //onmouseover lis[i].onmouseover = function(){ //當滑鼠滑過,改變className之前,將原來的className暫時儲存起來 this.oldClassName = this.className; //lis[i].className = "bg3";//迴圈內部設定事件函數,事件函數再迴圈執行完畢之後才會執行; this.className = "bg3"; } //滑鼠離開事件onmouseout lis[i].onmouseout = function(){ //怎麼樣才能回到原來的樣式呢 //涉及到html裡面怎麼去添加一個自訂屬性 this.className = this.oldClassName; } } </script></html>
js實現隔行變色