width()方法獲取或設(shè)置所選元素的寬度。
當(dāng)使用width()方法獲取寬度時(shí),它將返回第一個(gè)選定元素的寬度。
當(dāng)使用width()方法設(shè)置寬度時(shí),它將設(shè)置所有選定元素的寬度。
如下圖所示,width()方法不包含填充,邊框或邊距:

寬度值也可以是相對(duì)的。如果為值提供了前導(dǎo)+=或-=字符序列,則通過從當(dāng)前值中加上或減去給定的數(shù)字來計(jì)算目標(biāo)寬度(例如width(“-= 250”))。
得到寬度:
$(selector).width()
設(shè)置寬度:
$(selector).width(value)
使用函數(shù)設(shè)置寬度:
$(selector).width(function(index, currentWidth))
獲取DIV元素的寬度:
$("div").click(function(){
$(this).width();
});測(cè)試看看?/?設(shè)置所有段落的寬度:
$("button").click(function(){
$("p").width(250);
});測(cè)試看看?/?使用不同的單位設(shè)置所有段落的寬度:
$("#btn1").click(function(){
$("p").width(250);
});
$("#btn2").click(function(){
$("p").width("7em");
});
$("#btn3").click(function(){
$("p").width("100vw");
});測(cè)試看看?/?單擊按鈕時(shí),減小所有段落的寬度(使用函數(shù)):
$("button").click(function(){
$("p").width(function(i, val){
return val - 50;
});
});測(cè)試看看?/?width()方法還能夠找到窗口和文檔的寬度:
$(window).width();// 返回瀏覽器視口的寬度 $(document).width(); //返回HTML文檔的寬度測(cè)試看看?/?
顯示width(),height(),innerHeight(),innerWidth(),outerWidth()和outerHeight()之間的差異:
$("button").click(function(){
$("div").width();
$("div").innerWidth();
$("div").outerWidth();
$("div").height();
$("div").innerHeight();
$("div").outerHeight();
});測(cè)試看看?/?| 參數(shù) | 描述 |
|---|---|
| value | 表示像素?cái)?shù)的整數(shù),或附加了可選度量單位的整數(shù)(作為字符串) |
| function(index, currentWidth) | 指定一個(gè)函數(shù),該函數(shù)返回所選元素的寬度
|