JavaScript實例詳解之HTML元素操作( 三 )


HTML5解決方案:p元素對象.classList.toggle(“header”);
舉個例子

JavaScript實例詳解之HTML元素操作

文章插圖

代碼實現
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>classList的使用</title> <style> .bg{background:#ccc;} .strong{font-size:24px;color:red;} .smooth{height:30px;width:120px;border-radius:10px;} </style> </head> <body> <ul> <li>PHP</li> <li class="bg">JavaScript</li> <li>C++</li> <li>Java</li> </ul> <script> // 獲取第2個li元素 var ele = document.getElementsByTagName('li')[1]; // 若li元素中沒有strong類 , 則添加 if (!ele.classList.contains('strong')) { ele.classList.add('strong'); } // 若li元素中沒有smooth類 , 則添加;若有刪除 ele.classList.toggle('smooth'); console.log('添加與切換樣式后:'); console.log(ele); </script> <script> ele.classList.remove('bg'); console.log('刪除后:'); console.log(ele); </script> </body> </html>除此之外 , classList屬性還提供了許多其他相關操作的方法和屬性 。
JavaScript實例詳解之HTML元素操作

文章插圖

五、【案例】標簽欄切換效果

JavaScript實例詳解之HTML元素操作

文章插圖

代碼實現思路:
    ① 編寫HTML , 實現標簽欄的結構與樣式的設計 , 其中class等于current表示當前顯示的標簽 , 默認是第一個標簽 。
    ② 獲取所有的標簽與標簽對應的顯示內容 。
    ③ 遍歷并為每個標簽添加鼠標滑過事件 , 在事件的處理函數中 , 遍歷標簽對應的所有顯示內容 , 當鼠標滑過標簽時 , 通過classList的add()方法添加current , 否則通過remove()方法移出current 。
代碼實現
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>標簽欄切換效果</title> <style> .tab-box{width:383px;margin:10px;border:1px solid #ccc;border-top:2px solid #206F96;} .tab-head{height:31px;} .tab-head-p{width:95px;height:30px;float:left;border-bottom:1px solid #ccc;border-right:1px solid #ccc;background:#206F96;line-height:30px;text-align:center;cursor:pointer;color:#fff;} .tab-head .current{background:#fff;border-bottom:1px solid #fff;color:#000;} .tab-head-r{border-right:0;} .tab-body-p{display:none;margin:20px 10px;} .tab-body .current{display:block;} </style> </head> <body> <p class="tab-box"> <p class="tab-head"> <p class="tab-head-p current">標簽一</p> <p class="tab-head-p">標簽二</p> <p class="tab-head-p">標簽三</p> <p class="tab-head-p tab-head-r">標簽四</p> </p> <!--jkdjfk?--> <p class="tab-body"> <p class="tab-body-p current"> 1 </p> <p class="tab-body-p"> 2 </p> <p class="tab-body-p"> 3 </p> <p class="tab-body-p"> 4 </p> </p> </p> <script> // 獲取標簽欄的所有標簽元素對象 var tabs = document.getElementsByClassName('tab-head-p'); // 獲取標簽欄的所有內容對象 var ps = document.getElementsByClassName('tab-body-p'); for (var i = 0; i < tabs.length; ++i) { // 遍歷標簽部分的元素對象 tabs[i].onmouseover = function() { // 為標簽元素對象添加鼠標滑過事件 for (var i = 0; i < ps.length; ++i) { // 遍歷標簽欄的內容元素對象 if (tabs[i] == this) { // 顯示當前鼠標滑過的li元素 ps[i].classList.add('current'); tabs[i].classList.add('current'); } else { // 隱藏其他li元素 ps[i].classList.remove('current'); tabs[i].classList.remove('current'); } } }; } </script> </body> </html>相關推薦:javascript教程
以上就是JavaScript實例詳解之HTML元素操作的詳細內容 , 更多請關注電腦自學網其它相關文章!

推薦閱讀