如何用js在DOM中添加/刪除class命名

來源:互聯網
上載者:User

標籤:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>無標題文檔</title><style>*{ padding:0; margin:0;}#div1{ width:910px; border:1px solid #000; overflow:hidden; height:200px; padding:20px 0; position:relative}#div1 .active{ background:#FF0; border:1px solid #000; }#div1 div{ border:1px solid #F00; width:200px; height:200px; float:left; margin:0 10px; }#div1 .list{ position:absolute; top:0; margin-left:0;}#div1 .list1{ position:absolute; top:20px; left:20px;}#div1 .list2{ position:absolute; top:20px; left:240px;}#div1 .list3{ position:absolute; top:20px;left:460px;}#div1 .list4{ position:absolute; top:20px; left:680px;}</style><script>window.onload=function(){  var oDiv1=document.getElementById(‘div1‘);  var oBtn=oDiv1.getElementsByTagName(‘div‘);  for(var i=0; i<oBtn.length; i++){  oBtn[i].onmouseover=function(){  for(var i=0; i<oBtn.length;i++){  var classVal = oBtn[i].getAttribute("class");       classVal = " " + classVal + " ";       classVal = classVal .replace(" active ","");              oBtn[i].setAttribute("class",classVal );       }   var classVal = this.getAttribute("class");    classVal = " " + classVal + " ";   classVal = classVal.concat(" active");   this.setAttribute("class",classVal );s      }    };}</script></head><body><div id="div1">   <div class="list list1"></div>   <div class="list list2"></div>   <div class="list list3"></div>   <div class="list list4"></div></div></body></html>

 以上代碼就可以

藉此機會,介紹一下replace和concat的用法

replace定義和用法

replace() 方法用於在字串中用一些字元替換另一些字元,或替換一個與Regex匹配的子串。

stringObject.replace(regexp/substr,replacement)

http://www.w3school.com.cn/jsref/jsref_replace.asp

concat定義和用法

concat() 方法用於串連兩個或多個數組。

<html><body><script type="text/javascript">var a = [1,2,3];document.write(a.concat(4,5));</script></body></html>

 結果是1,2,3,4,5

如何用js在DOM中添加/刪除class命名

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.