摘要:課程中案例:<!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>
運(yùn)行截圖:
總結(jié):
document.getElementById()返回的是頁面元素。
document.getElementsByClassName()返回的是頁面元素的數(shù)組,訪問其內(nèi)容需要下標(biāo)。
實(shí)際操作中遇到的一個(gè)小問題,搞了半天終于搞懂。
批改老師:天蓬老師批改時(shí)間:2019-06-29 13:29:41
老師總結(jié):準(zhǔn)確的講: document.getElementsByClassName(), 返回的不是一個(gè)真正的數(shù)組, 你可以用Array.isArray()判斷就知道了, 它返回的是一個(gè)類數(shù)組對(duì)象, 就是看上去比較像數(shù)組的對(duì)象, 內(nèi)部的每一個(gè)成員, 實(shí)際上仍是一個(gè)元素對(duì)象而已, 不過它又像數(shù)組一樣有l(wèi)ength屬性, 但去不能用數(shù)組方法來處理它...,
例如, 無法用forEach, push等方法