DOM獲取元素大小

2021-07-10 21:28:49 字數 2607 閱讀 7769

1.style獲取行內的元素大小

var box = document.getelementbyid('box');

alert(typeof box.style.width);

alert(box.style.height);

2.獲取計算後的css大小,如果沒有設定,非ie會獲取預設大小,ie會理解為0

var style = window.getcomputedstyle?window.getcomputedstyle(box,null):null||box.currentstyle;

alert(style.width);

alert(style.height);

3.使用cssstylesheet物件中的cssrules屬性(rules)

ps:cssrules(rule)只能獲取到內聯和鏈結樣式的寬和高,不能獲取行內和計算後的樣式

var sheet = document.stylesheets[0];

var rule = (sheet.cssrules||sheet.rules)[0];

alert(rule.style.width);

alert(rule.style.height);

總結:這三種都不能獲取實際大小(比如設定乙個內邊距,獲取大的大小不會包含內邊距)

獲取實際大小

1.(clientwidth和clientheight)即獲取的是元素可視區域的大小

alert(box.clientwidth); //沒有單位,但預設是px

alert(box.clientheight);

//alert(typeof box.clientheight); //number ,返回的資料型別是數字,不是字串了

//如果設定了其他的單位,返回出來的結果還會轉換為px畫素

//增加邊框和外邊距,無變化,是不算在clientwidth 和clientheight的實際大小裡面的

//內邊距會增加實際大小,最終值等於原本大小+內邊距的大小

//增加滾動條會減少實際大小,最終值等於原來的值減去滾動條的大小

//在沒有內邊距和滾動條的情況下,沒有設定css大小,那麼ie為理解為0

2.scrollwidth scrollheight 獲取的是滾動內容的元素大小(不太穩定)

alert(box.scrollwidth);

alert(box.scrollheight);

//增加邊框 不同的瀏覽器有不同的解釋

//增加內邊距 最終值等於原本大小+內邊距的大小

//增加外邊距 無變化

//增加滾動條,最終值會等於原本大小減去滾動條的大小

//如果文字溢位,沒加滾動條,不同的瀏覽器也不太相容

//有溢位 加上滾動條方可相容(ps:我的不相容)

3. offsetwidth offsetheight 這組屬性返回元素實際大小

alert(box.offsetwidth);

alert(box.offsetheight);

//ps:這組屬性穩定性好

//增加邊框,最終值等於原本大小加上邊框大小

//增加內邊距,最終智等於原本大小加上內邊距大小

//增加外邊距和滾動條,無變化

獲取元素周邊大小

1.clientleft和clienttop  獲取元素設定了左邊框和上邊框的大小

alert(box.clienttop); //獲取左邊框的長度

alert(box.clientleft); //獲取上邊框的長度

2.offsetleft 和offsettop //則組屬性獲取當前元素相對于父元素的位置

alert(box.offsetleft);

alert(box.offsettop);

//ps:獲取當前相對于父元素的位置,最好將它設為定位position:absolute;否則不同的瀏覽器會有不同的解釋

//加上邊框和內邊距不會影響它的位置,但加上外邊距會累加

//alert(box.offsetparent.tagname); //獲取父元素

//如果沒有設定定位 會產生很多問題

// alert(box.offsettop+box.offsetparent.offsettop);// 求出box距離頁面口直接的距離

alert(offsettop(box))

//如果有多層 累加

function

offsettop

(element)

return top;

}3. scrolltop 和scrollleft //這組屬性可以設定滾動條被隱藏的區域大小,也可設定定位到該區域

//alert(box.scrolltop);

//alert(box.scrollleft);

//alert(box.scrolltop);

box.scrolltop=35;

//如果不在0的位置 讓它回到0位置

function

scrollstart

(element)

}

JS獲取DOM元素位置與大小

每乙個html元素都有以下屬性 offsetwidth offsetheight offsetleft offsettop clientwidth clientheight scrollwidth scrollheight scrollleft scrolltop screenx screeny o...

DOM元素的獲取

通過id獲取元素 document.getelementbyid id 通過class獲取元素 document.getelementsbyclassname class 注意 這裡不相容ie8及以下,jq的話獲取class不影響這裡,假如要這樣操作的話,你需要寫個方法 function getel...

angular 獲取 DOM 元素

viewchild配合local template variable 原生元素可以通過local variable獲取。在寫元件時,我們可以直接在元件模版裡給這個 input 標籤加標記 譬如 myinput 然後把標記傳給 viewchild用來獲取該元素。當元件初始化後,你就可以通過 rende...