abstract:課程中案例:<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>JavaScript控制div樣式</title> &nbs
課程中案例:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>JavaScript控制div樣式</title> <style> div { width: 100px; height: 100px; background-color: #bb60d5; margin-bottom: 30px; } </style> </head> <body> <div id="box"></div> <input type="button" value="變高" onclick="aa()"> <input type="button" value="變寬" onclick="bb()"> <input type="button" value="變色" onclick="cc()"> <input type="button" value="重置" onclick="dd()"> <input type="button" value="隱藏" onclick="ee()"> <input type="button" value="顯示" onclick="ff()"> <script> var box ; window.onload = function (){ box = document.getElementById('box'); } function aa() { box.style.height = "300px"; } function bb() { box.style.width = "300px"; } function cc() { box.style.backgroundColor = "red"; } function dd() { box.style.width = "100px"; box.style.height = "100px"; box.style.backgroundColor = "#bb60d5"; box.style.display = 'block'; } function ee() { box.style.display = 'none'; } function ff() { box.style.display = 'block'; } </script> </body> </html>
運行截圖:
總結:
document.getElementById()返回的是頁面元素。
document.getElementsByClassName()返回的是頁面元素的數(shù)組,訪問其內容需要下標。
實際操作中遇到的一個小問題,搞了半天終于搞懂。
Correcting teacher:天蓬老師Correction time:2019-06-29 13:29:41
Teacher's summary:準確的講: document.getElementsByClassName(), 返回的不是一個真正的數(shù)組, 你可以用Array.isArray()判斷就知道了, 它返回的是一個類數(shù)組對象, 就是看上去比較像數(shù)組的對象, 內部的每一個成員, 實際上仍是一個元素對象而已, 不過它又像數(shù)組一樣有l(wèi)ength屬性, 但去不能用數(shù)組方法來處理它...,
例如, 無法用forEach, push等方法