摘要:课程中案例:<!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()返回的是页面元素的数组,访问其内容需要下标。
实际操作中遇到的一个小问题,搞了半天终于搞懂。
批改老师:天蓬老师批改时间:2019-06-29 13:29:41
老师总结:准确的讲: document.getElementsByClassName(), 返回的不是一个真正的数组, 你可以用Array.isArray()判断就知道了, 它返回的是一个类数组对象, 就是看上去比较像数组的对象, 内部的每一个成员, 实际上仍是一个元素对象而已, 不过它又像数组一样有length属性, 但去不能用数组方法来处理它...,
例如, 无法用forEach, push等方法