jQuery - Dimensions (尺寸)
使用 jQuery,可以輕鬆處理元素和瀏覽器視窗的尺寸。
jQuery Dimension (尺寸) 方法
jQuery 提供了幾個重要的尺寸處理方法:
width()
height()
innerWidth()
innerHeight()
outerWidth()
outerHeight()
jQuery Dimensions (尺寸)
jQuery width() 和 height() 方法
width()
方法用於設定或返回元素的寬度(不包括 padding、border 和 margin)。
height()
方法用於設定或返回元素的高度(不包括 padding、border 和 margin)。
以下示例返回指定 <div>
元素的寬度和高度:
示例
$("button").click(function(){
var txt = "";
txt += "Width: " + $("#div1").width() + "</br>";
txt += "Height: " + $("#div1").height();
$("#div1").html(txt);
});
自己動手試一試 »
jQuery innerWidth() 和 innerHeight() 方法
innerWidth()
方法返回元素的寬度(包括 padding)。
innerHeight()
方法返回元素的高度(包括 padding)。
以下示例返回指定 <div>
元素的內部寬度/高度:
示例
$("button").click(function(){
var txt = "";
txt += "Inner width: " + $("#div1").innerWidth() + "</br>";
txt += "Inner height: " + $("#div1").innerHeight();
$("#div1").html(txt);
});
自己動手試一試 »
jQuery outerWidth() 和 outerHeight() 方法
outerWidth()
方法返回元素的寬度(包括 padding 和 border)。
outerHeight()
方法返回元素的高度(包括 padding 和 border)。
以下示例返回指定 <div>
元素的外部寬度/高度:
示例
$("button").click(function(){
var txt = "";
txt += "Outer width: " + $("#div1").outerWidth() + "</br>";
txt += "Outer height: " + $("#div1").outerHeight();
$("#div1").html(txt);
});
自己動手試一試 »
outerWidth(true)
方法返回元素的寬度(包括 padding、border 和 margin)。
outerHeight(true)
方法返回元素的高度(包括 padding、border 和 margin)。
示例
$("button").click(function(){
var txt = "";
txt += "Outer width (+margin): " + $("#div1").outerWidth(true) + "</br>";
txt += "Outer height (+margin): " + $("#div1").outerHeight(true);
$("#div1").html(txt);
});
自己動手試一試 »
jQuery 更多 width() 和 height() 應用
以下示例返回文件(HTML 文件)和視窗(瀏覽器視口)的寬度和高度:
示例
$("button").click(function(){
var txt = "";
txt += "Document width/height: " + $(document).width();
txt += "x" + $(document).height() + "\n";
txt += "Window width/height: " + $(window).width();
txt += "x" + $(window).height();
alert(txt);
});
自己動手試一試 »
以下示例設定指定 <div>
元素的寬度和高度:
jQuery 練習
jQuery CSS 參考
有關所有 jQuery CSS 方法的完整概述,請訪問我們的 jQuery HTML/CSS 參考。