Python開發【第十二篇】:DOM
阿新 • • 發佈:2018-11-08
http://www.cnblogs.com/wupeiqi/articles/5643298.html
文件物件模型(Document Object Model,DOM)是一種用於HTML和XML文件的程式設計介面。它給文件提供了一種結構化的表示方法,可以改變文件的內容和呈現方式。我們最為關心的是,DOM把網頁和指令碼以及其他的程式語言聯絡了起來。DOM屬於瀏覽器,而不是JavaScript語言規範裡的規定的核心內容。
一、查詢元素
1、直接查詢
1 2 3 4 |
document.getElementById 根據
ID
獲取一個標籤
document.getElementsByName 根據name屬性獲取標籤集合
document.getElementsByClassName 根據 class
屬性獲取標籤集合
document.getElementsByTagName 根據標籤名獲取標籤集合
|
2、間接查詢
1 2 3 4 5 6 7 8 9 10 11 12 13 |
parentNode
/
/
父節點
childNodes
/
/
所有子節點
firstChild
/
/
第一個子節點
lastChild
/
/
最後一個子節點
nextSibling
/
/
下一個兄弟節點
previousSibling
/
/
上一個兄弟節點
parentElement
/
/
父節點標籤元素
children
/
/
所有子標籤
firstElementChild
/
/
第一個子標籤元素
lastElementChild
/
/
最後一個子標籤元素
nextElementtSibling
/
/
下一個兄弟標籤元素
previousElementSibling
/
/
上一個兄弟標籤元素
|
二、操作
1、內容
1 2 3 4 5 |
innerText 文字
outerText
innerHTML HTML內容
innerHTML
value 值
|
2、屬性
1 2 3 4 5 6 7 8 9 |
attributes
// 獲取所有標籤屬性
setAttribute(key,value)
// 設定標籤屬性
getAttribute(key)
// 獲取指定標籤屬性
/*
var atr = document.createAttribute("class");
atr.nodeValue="democlass";
document.getElementById('n1').setAttributeNode(atr);
*/
|
3、class操作
1 2 3 |
className
// 獲取所有類名
classList.remove(cls)
// 刪除指定類
classList.add(cls)
// 新增類
|
4、標籤操作
a.建立標籤
1 2 3 4 5 6 7 8 |
// 方式一
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>"
|
b.操作標籤
1 2 3 4 5 6 7 8 9 10 11 |
// 方式一
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])
|
5、樣式操作
1 2 3 4 |
var
obj = document.getElementById(
'i1'
)
obj.style.fontSize =
"32px"
;
obj.style.backgroundColor =
"red"
;
|
6、位置操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
總文件高度
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代指文件根節點
*/
|
7、提交表單
1 |
document.geElementById(
'form'
).submit()
|
8、其他操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
console.log 輸出框
alert 彈出框
confirm 確認框
// URL和重新整理
location.href 獲取URL
location.href =
"url"
重定向
location.reload() 重新載入
// 定時器
setInterval 多次定時器
clearInterval 清除多次定時器
setTimeout 單次定時器
clearTimeout 清除單次定時器
|
三、事件
對於事件需要注意的要點:
- this
- event
- 事件鏈以及跳出
this標籤當前正在操作的標籤,event封裝了當前事件的內容。
例項:
搜尋框 跑馬燈