js動態改變css樣式
阿新 • • 發佈:2019-02-14
- 動態改變頁面元素樣式:
- 使用getElement系列方法訪問元素。
- 改變樣式屬性:style屬性;className屬性。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script type="application/javascript" src="js/動態改變css.js"></script> <style type="text/css"> .menu{ width: 100px; height: 30px; border-top-left-radius:10px ; border-top-right-radius: 10px; background-color: darkgray; text-align: center; padding-top: 4px; } .menuOver{ background-color: orange; width: 100px; height: 30px; border-top-left-radius:10px ; border-top-right-radius: 10px; text-align: center; padding-top: 4px; } .menuOut{ background-color: darkgray; width: 100px; height: 30px; border-top-left-radius:10px ; border-top-right-radius: 10px; text-align: center; padding-top: 4px; } .first_ul{ list-style: none; } .first_ul li{ float: left; background-color: #F79337; font-size: 14px; font-weight: bold; color: white; border-radius: 5px; width: 70px; height: 30px; text-align: center; padding-top: 10px; } </style> </head> <body> <!--修改css樣式,單擊:onclick--> <div id="content1">DIV樣式</div> <input type="button" name="" id="" value="改變樣式" onclick="btn1()";/> <hr /> <!--滑鼠移入onmouseover移出onmouseout滑鼠按鈕按下--> <div id="menuObj" class="menu" onmouseover="setMenuBgColor(this,1)"; onmouseout="setMenuBgColor(this,2)";> 商品類別 </div> <hr /> <!--同時改變所有li的樣式--> <ul class="first_ul"> <li>首頁</li> <li>家用電器</li> <li>手機數碼</li> <li>日用百貨</li> <li>書籍</li> </ul> </body> </html>
function btn1(){ /* * 改變div元素背景 * 元素中間橫線去掉,第二個首字母也大寫 */ document.getElementById("content1").style.backgroundColor="red"; } //利用obj引數傳入this可以使方法複用 function setMenuBgColor(obj,flag){ switch(flag){ case 1: // 1.通過物件中的style屬性來修改css樣式效果 // 滑鼠移入 // document.getElementById("menuObj").style.backgroundColor="orange"; // obj.style.backgroundColor="orange"; // 2.通過類選擇器來修改CSS樣式效果 obj.className = "menuOver"; //只需要加樣式名,不用. break; case 2: // 滑鼠移出 // document.getElementById("menuObj").style.backgroundColor="darkgray"; // obj.style.backgroundColor="darkgray"; obj.className = "menuOut"; break; } } window.onload=function(){ // 同時改變所有li的樣式 var objli=document.getElementsByTagName("li"); for (var i=0;i<objli.length;i++) { objli[i].onmouseover=function(){ this.style.backgroundColor="red"; } objli[i].onmouseout=function(){ this.style.backgroundColor="#F79337"; } } }