JavaScript DOM和BOM

259 阅读2分钟

文档对象模型

DOM把文档当作一个对象来看待
DOM的顶级对象是document
DOM的主要学习是操作页面元素
DOM是W3C标准规范

DOM的各类方法

获取标签节点

父.appendChild(标签) - 将标签插入到父标签的末尾

父.insertBefore(新的标签, 旧的子标签) - 将新标签添加到父标签中已经存在的某个子标签的前面

document.body.appendChild(div)
document.body.insertBefore(div, ul)

获取标签

获取子标签 - 父.children

console.log( ul.children );

获取某个标签的上一个兄弟标签

标签.previousElementSibling

var fourth = document.querySelector('.fourth')
console.log(fourth);
console.log( fourth.previousElementSibling );

下一个兄弟标签

标签.nextElementSibling

console.log ( fourth.nextElementSibling );

获取父标签

子.parentElement

console.log( fourth.parentElement );

第一个子

父.firstElementChild

 console.log( ul.firstElementChild );

最后一个子

父.lastElementChild

console.log( ul.lastElementChild );

替换标签

父.replaceChild(新, 旧的子标签)

ul.replaceChild(b, fourth)

删除标签

父.removeChild(子)

ul.removeChild(fourth)

复制标签

标签.cloneNode()

console.log( fourth.cloneNode() );
// 如果要将标签中的内容和子标签都复制出来,就给方法添加参数true
console.log( fourth.cloneNode(true) );

直接获取到标签大小 --- 数字

不带边框的大小

标签.clientWidth

标签.clientHeight

var box = document.querySelector('.box')
var w1 = box.clientWidth
var h1 = box.clientHeight
console.log(w1, h1);
带边框的大小

标签.offsetWidth

标签.offsetHeight

var w2 = box.offsetWidth
var h2 = box.offsetHeight
console.log(w2, h2);

获取标签的位置 --- 数字

参照设置过定位的直系祖宗标签

标签.offsetLeft

标签.offsetTop

var l1 = big.offsetLeft
var t1 = big.offsetTop
console.log(l1, t1);

var small = document.querySelector('.small')
var l2 = small.offsetLeft
var t2 = small.offsetTop
console.log(l2, t2);

边框厚度

标签.clientLeft

标签.clientTop

var box = document.querySelector('.box')
var l = box.clientLeft
console.log(l);

var t = box.clientTop
console.log(t);

窗口大小不包含滚动条

document.documentElement.clientWidth

document.documentElement.clientHeight

var w1 = innerWidth
var h1 = innerHeight
var w2 = document.documentElement.clientWidth
var h2 = document.documentElement.clientHeight
console.log(w1, h1);
console.log(w2, h2);

浏览器对象模型

BOM把浏览器当作一个对象来看待
BOM的顶级对象是window
BOM学习的是浏览器窗口交互的一些对象
BOM是浏览器厂商在各自浏览器上定义的,兼容性较差
BOM概述
BOM(Browser Object Model)即浏览器对象模型,它提供了独立于内容而与浏览器窗口进行交互的对象,其核心对象是window;