- 獲取元素的方法常用API
getElementById
getElementsByName
getElementsByTagName
getElementsByClassName
querySelectorAll //通過css選擇器
- getElementById與querySelectorAll區(qū)別
getElementById等是實(shí)時(shí)的
querySelectorAll是靜態(tài)的NodeList集合安吁,IE8以上支持
x = document.querySelectorAll('img')
y = document.getElementsByTagName('img')
document.body.appendChild(new Image())
x.length // 0
y.length // 1
Node的重要屬性醉蚁,注意:文本也是Node
parentNode 、childNodes 鬼店、firstChild网棍、lastChild、nextSibling妇智、previoursSibling
上面的很容易理解滥玷,不多解釋
nodeType
1 代表Element節(jié)點(diǎn) 3代表Text節(jié)點(diǎn) 8代表Comment節(jié)點(diǎn) 9代表Document 11 代表DocumentFragment節(jié)點(diǎn)
nodeValue
Text或Comment節(jié)點(diǎn)內(nèi)容
nodeName
元素的大寫標(biāo)簽名屬性
getAttribute()不返回?cái)?shù)值氏身、布爾值或?qū)ο?br> setAttribute("class","test")設(shè)置屬性
removeAttribute()
hasAttribute()
attributes 屬性集合,實(shí)時(shí)的創(chuàng)建、插入和刪除節(jié)點(diǎn)
創(chuàng)建
document.createElement("script")
document.createTextNode("")
document.createDocumentFragment() //性能考慮容器
function reverse(n){
var f=document.createDocumentFragment();
while(n.lastChild){
f.appendChild(n.lastChild)
}
n.appendChild(f);
}
插入
父.appendChild(子) //子已有則是剪切粘貼
父.insertBefore(新節(jié)點(diǎn)惑畴,已有節(jié)點(diǎn) ) //根據(jù)語義蛋欣,參數(shù)順序新的在舊的之前
刪除
父.removeChild()
父.replaceChild(新節(jié)點(diǎn),已有節(jié)點(diǎn)) //新的替代舊的
- 文檔坐標(biāo)和視口坐標(biāo)
scrollLeft和scrollTop獲取已經(jīng)滾動(dòng)的距離
function getScrollOffsets(w){
w =w ||window;
if(w.pageXOffset !=null){
return {x:w.pageXOffset ,y:pageYOffset }
}
var d=w.document;
if(document.compatMode =="CSS1Compat"){
return {x:document.documentElement.scrollLeft ,y:document.documentElement.scrollTop }
}
else{
return {x:document.body.scrollLeft ,y:document.body.scrollTop }
}
}
獲取視口的尺寸
function getViewportSize(w) {
w =w||window;
if(w.innerHeight !=null){
return {x:w.innerWidth,y:w.innerHeight};
}
if(document.compatMode == "CSS1Compat"){
return {
x:document.documentElement.clientWidth,
y:document.documentElement.clientHeight
}
}else{
return {
x:document.body.clientWidth,
y:document.body.clientHeight
}
}
}
獲取元素的尺寸
getBoundingClientRect()返回元素的left top right bottom如贷,兼容性很棒
除了IE之外陷虎,其他瀏覽器會(huì)有width、height值
視口坐標(biāo)+滾動(dòng)條位置 =文檔坐標(biāo)
- 滾動(dòng)
window.scrollTo() window.scrollTop()
window.scrollBy(0,10) 坐標(biāo)是相對(duì)的
offsetHeight offsetWidth返回width+padding+border
offsetLeft offsetTop 相對(duì)于定位父元素的
offsetParent 父元素
clientWidth clientHeight //返回width+padding
clientLeft 杠袱、clientTop // 左尚猿、上邊框的寬度
- 其他
window.getSelection().toString()
document.selection.createRange().text
contenteditable
visibility hidden/visible 文檔中仍保留其位置
display none
隱藏和顯示定位元素時(shí),首選visibility
e.style.left = "300px" 定位屬性必須為字符串有單位
document.styleSheets 表示與文檔關(guān)聯(lián)的樣式表
數(shù)組元素為CSSStyleSheet對(duì)象楣富,元素為 一個(gè)cssRules[]數(shù)組凿掂,元素為樣式規(guī)則
var firstRule = document.styleSheets[0].CSSStyleSheet[0]
insertRule deleteRule IE下 addRule removeRule
document.createStyleSheet //添加樣式