1.7 元素对象
题目:
控制台:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box {
box-sizing: border-box;
width: 200px;
height: 200px;
border: 3px solid lightskyblue;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
let box = document.getElementById('box');
box.style.backgroundColor = 'red';
let AA = box.style;
AA.backgroundColor = 'blue';
let BB = box.style.backgroundColor;
BB = 'orange';
</script>
</body>
</html>
解析
<body>
<div id="box"></div>
<script>
let box = document.getElementById('box');
console.log(typeof box); // => 'object'
// 1. 通过方法方法方法获取的元素是对象数据类型的值
console.dir(box);
// 2. 基于 dir 可以看出对象的详细信息(属性)
/*
各种属性:
id: 操作元素的 ID 值
className: 操作元素的CLASS样式类值
innerHTML: 操作元素的内容(可以识别标签)
innerText: 和 innerHTML 的区别是不能识别标签
onclick: 又是属性名,又是事件绑定
所以可以写成 box['onclick'] = function (){}
style: 操作元素的行内样式
tagName : 获取元素的标签名(一般大写)
...
*/
// 3. style 属性 属性值是一个新的对象 : CSSStyleDeclaration
// 就是因为 style 属性值是对象,所以才能 元素.style.xxx 来操作对象
// 看图 1 - 1
box.style.backgroundColor = 'red';
let AA = box.style;
AA.backgroundColor = 'blue';
// 因为修改的是堆内存中的值,所以 AA起作用
// 只要堆内存的值被修改,浏览器会基于 DOM 映射机制(后面将)把页面中的元素进行重新渲染
let BB = box.style.backgroundColor;
BB = 'orange';
// 只是修改了 BB 的值,没有修改堆内存中的内容
// 结论,box 存储的是引用类型的值,需要通过地址来操作堆中信息
// BB 只是在操作基本类型值,所以未能生效
</script>
</body>
属性 style 图解
多维对象: 对象属性里属性值是对象类型
图 1 - 1
题目图解
修改 AA
修改 BB