outerWidth()和width()的區(qū)別
outerWidth(includeMargin) : 獲取元素集合中第一個元素的當前計算寬度值。包括這個元素的 padding,border,如果 includeMargin 的值被設置為 true,那么 margin 的值也將被計算在寬度之內。includeMargin 的值默認為 false。該方法不適用于 window 和 document 對象。
width(value) : 為匹配的元素集合中獲取第一個元素的當前計算寬度值。該方法適用于計算 window 和 document 對象的寬度。當調用 .width(value)方法 的時候,這個“value”參數可以是一個字符串(數字加單位)或者是一個數字。如果這個“value”參數只提供一個數字,jQuery會 自動加上單位px。如果只提供一個字符串,任何有效的CSS尺寸都可以為寬度賦值(就像100px, 50%, 或者 auto)。
另外 JS 中還提供了 document.body.clientWidth 來獲取 body 的寬度,如果要使元素始終保持上下左右居中,而不隨著瀏覽器窗口變化而變化,就可以使用該方法來實現。
下面是一段使元素保持上下左右居中的代碼(注意居中的元素css需設置position)。
function center(node){
centerFun(node);
//瀏覽器窗口發(fā)生變化時仍然居中
$(window).resize(function(){
centerFun(node);
});
//滾動條滾動時仍然居中
$(window).scroll(function(){
centerFun(node);
});
}
function centerFun(node){
var windowWidth = $(window).width();
var windowHeight = $(window).height();
var scrollTop = $(document).scrollTop();
var nodeLeft = (windowWidth - node.width())/2;
var nodeHeight = (windowHeight - node.height())/2 + scrollTop;
node.css({left: nodeLeft + 'px',top: nodeHeight + 'px',display: 'block'});
}
center($("#box"));