WEB前端-DOM-基本使用

文檔對象模型(Document Object Model,DOM)是一種用於HTML和XML文檔的編程接口。它給文檔提供了一種結構化的表示方法,可以改變文檔的內容和呈現方式。我們最爲關心的是,DOM把網頁和腳本以及其他的編程語言聯繫了起來。DOM屬於瀏覽器,而不是JavaScript語言規範裏規定的核心內容。

一、查找元素

1、直接查找

document.getElementById             根據ID獲取一個標籤
document.getElementsByName          根據name屬性獲取標籤集合
document.getElementsByClassName     根據class屬性獲取標籤集合
document.getElementsByTagName       根據標籤名獲取標籤集合

2、間接查找

parentNode          // 父節點
childNodes          // 所有子節點
firstChild          // 第一個子節點
lastChild           // 最後一個子節點
nextSibling         // 下一個兄弟節點
previousSibling     // 上一個兄弟節點

parentElement           // 父節點標籤元素
children                // 所有子標籤
firstElementChild       // 第一個子標籤元素
lastElementChild        // 最後一個子標籤元素
nextElementtSibling     // 下一個兄弟標籤元素
previousElementSibling  // 上一個兄弟標籤元素

二、操作

1、內容

innerText   文本
outerText
innerHTML   HTML內容
innerHTML  
value

2、屬性

attributes                // 獲取所有標籤屬性
setAttribute(key,value)   // 設置標籤屬性
getAttribute(key)         // 獲取指定標籤屬性

/*
var atr = document.createAttribute("class");
atr.nodeValue="democlass";
document.getElementById('n1').setAttributeNode(atr);
*/

3、class

className                // 獲取所有類名
classList.remove(cls)    // 刪除指定類
classList.add(cls)       // 添加類

4、標籤

創建標籤

// 方式一:對象形式(推薦使用)
var tag = document.createElement('a')
tag.innerText = "wupeiqi"
tag.className = "c1"
tag.href = "http://www.cnblogs.com/wupeiqi"

// 方式二:字符串形式
var tag = "<a class='c1' href='http://www.cnblogs.com/wupeiqi'>wupeiqi</a>"

插入標籤

// 方式一
var obj = "<input type='text' />";
xxx.insertAdjacentHTML("beforeEnd",obj);
xxx.insertAdjacentElement('afterBegin',document.createElement('p'))

//注意:第一個參數只能是'beforeBegin''afterBegin''beforeEnd''afterEnd'

// 方式二
var tag = document.createElement('a')
xxx.appendChild(tag)
xxx.insertBefore(tag,xxx[1])

樣式操作

var obj = document.getElementById('i1')

obj.style.fontSize = "32px";
obj.style.backgroundColor = "red";

位置操作

總文檔高度
document.documentElement.offsetHeight

當前文檔佔屏幕高度
document.documentElement.clientHeight

自身高度
tag.offsetHeight

距離上級定位高度
tag.offsetTop

父定位標籤
tag.offsetParent

滾動高度
tag.scrollTop

/*
    clientHeight -> 可見區域:height + padding
    clientTop    -> border高度
    offsetHeight -> 可見區域:height + padding + border
    offsetTop    -> 上級定位標籤的高度
    scrollHeight -> 全文高:height + padding
    scrollTop    -> 滾動高度
    特別的:
        document.documentElement代指文檔根節點
*/

表單提交

document.geElementById('form').submit()

其他操作

console.log                 輸出框
alert                       彈出框
confirm                     確認框

// URL和刷新
location.href               獲取URL
location.href = "url"       重定向
location.reload()           重新加載

// 定時器
setInterval                 多次定時器
clearInterval               清除多次定時器
setTimeout                  單次定時器
clearTimeout                清除單次定時器

三、事件
dom 事件 web 前端 開發

對於事件需要注意的要點:

this
event
事件鏈以及跳出
this標籤當前正在操作的標籤,event封裝了當前事件的內容。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章