var div = document.getElementsByTagName("div");
div.attributes.item(0) // HTML5 里的屬性 元素的屬性
div.classList.add('test') // 直接添加一個類
盒子模型屬性值
1. client (只讀)
clientWidth: 內(nèi)容的可視寬度(width)+ 左右 padding
clientHeight: 內(nèi)容的可視高度(height) + 上下 padding
clientLeft: 左邊框的寬度
clientTop: 上邊框的寬度
box.contentEditable = 'true' // 讓 box 可編輯
2. offset(只讀)
offsetWidth: clientWidth + 左右邊框
offsetHeight: clientHeight + 上下邊框
offsetTop: 當(dāng)前元素的外邊框距離父級參照物的內(nèi)邊距的偏移量。最小值 0 ,最大值:scrollHeight - clientHeight;
offsetLeft:
offsetParent: 當(dāng)前元素的父級參數(shù)物
3. scroll (scrollWidth、scrollHeight 只讀,scrollTop、scrollLeft 可修改)
scrollWidth : 沒有內(nèi)容溢出時, clientWidth 等于 scrollWidth
scrollHeight : 有內(nèi)容溢出時,真實(shí)內(nèi)容高度 + 上下填充
獲取到的結(jié)果是 “約等于” 的值,同一個瀏覽器,是否設(shè)置 overflow:'hidden',對最終結(jié)果是有影響的,不同瀏覽器中取得的值也是不同的。
scrollTop: 滾動條拉動過程中,看不到的內(nèi)容的高度。
scrollLeft: 滾動條拉動過程中,看不到的內(nèi)容的寬度。
2. js 盒子模型取值問題:
上面的屬性值獲取的結(jié)果都是整數(shù),瀏覽器在獲取結(jié)果的時候在真實(shí)的結(jié)果上進(jìn)行四舍五入處理。
3. 關(guān)于操作瀏覽器本身的盒子模型
獲取可視寬度:
document.documentElement.clientWidth || document.body.clientWidth
document.documentElement.clientHeight || document.body.clientHeight
頁面的真實(shí)寬度和高度:
document.documentElement.scrollWidth || document.body.scrollWidth
document.doucmentElement.scrollHeight || document.body.scrollHeight
兼容的寫法:
document.documentElement[attr] || document.body[attr]
兼容的方法獲取屬性值和設(shè)置屬性值:
/*
* 只傳遞了 attr 參數(shù),說明是獲取屬性的值,
* 如果傳遞 value ,說明是設(shè)置值
*/
function win(attr, value){
if(typeof value === 'undefined'){
return document.documentElement[attr]|| document.body[attr]
}
document.documentElement[attr] = value;
document.body[attr] = value;
}
window.getComputedStyle :獲取所有經(jīng)過瀏覽器計算后的樣式。(IE 6~8 下不兼容,沒有 getComputedStyle)
window.getComputedStyle(當(dāng)前要操作的對象,偽類),不用寫偽類寫 null
比如獲得高度:window.getComputedStyle(div,null).height
IE6~8 : 可以使用 currentStyle 來獲取所以經(jīng)過瀏覽器計算過的樣式。
border , fontFamily 標(biāo)準(zhǔn)瀏覽器和 IE 瀏覽器獲取到的結(jié)果不同,主要是 getComputedStyle 和 currentStyle 計算的結(jié)果不同。可以通過初始化一些樣式,避免瀏覽器之間的差異。
// 獲取當(dāng)前元素所以經(jīng)過瀏覽器計算過的樣式中的 [attr] 對應(yīng)的值
function getCss(curEle, attr){
var val = null, reg = null;
try{
if('getComputedStyle' in window){
val = window.getComputedStyle(curEle, null)[attr];
} // 這里可以不用 if
} catch (e){
if(attr === "opacity"){
val = curEle.currentStyle['filter'];
reg = /^alpha\(opacity=(\d+(?:\.\d+)?)\)$/i;
val = reg.test(val)?reg.exec(val)[1]/100:1;
}else{
val = curEle.currentStyle[attr];
}
}
reg = /^(-?\d+(\.\d+)?)(px|pt|rem|em)?/i;
return reg.test(val)?parseFloat(val):val; //去掉單位
}