2011-09-13 59 views
1

我有以下jQuery代碼,它可以找出容器的寬度,然後告訴子元素爲特定大小(減去側邊欄的大小),以便它填滿屏幕。即使瀏覽器窗口發生變化,jQuery也會查找元素寬度

它工作正常除了當用戶更改瀏覽器窗口它不更新!所以我需要jQuery代碼實時工作。誰能幫忙?謝謝

$(document).ready(function() { 

    // find out the width of the page 
    var pageWidth = $('div.MainContentHolder').width(); 
    // minus the sidebar and margin width 
    var middleWidth = pageWidth - '220'; 
    // apply the new width to the middle column 
    $('div.MiddleColumn').css('width', middleWidth); 

}); 

回答

1

移動代碼以一個單獨的函數,並具有它的document readywindow resize事件同時運行:順便提及

function resizeElements() { 
    // find out the width of the page 
    var pageWidth = $('div.MainContentHolder').width(); 
    // minus the sidebar and margin width 
    var middleWidth = pageWidth - '220'; 
    // apply the new width to the middle column 
    $('div.MiddleColumn').css('width', middleWidth); 
} 

$(document).ready(function() { 
    resizeElements(); 
    $(window).resize(resizeElements); 
} 
+0

,'$( 'div.MiddleColumn')寬度(middleWidth)'是比'$('div.MiddleColumn').css('width',middleWidth)'更好。使用'css'的速度較慢,無論如何要使用'### px'格式。 – Blazemonger

+0

@ mblase75:'.css()'將數字解釋爲'px'值(除了一些特定的CSS屬性,例如'z-index')。 –

3

你只需要將它綁定到$(window).resize();

$(document).ready(function() { 

    $(window).resize(function() { 
     // find out the width of the page 
     var pageWidth = $('div.MainContentHolder').width(); 
     // minus the sidebar and margin width 
     var middleWidth = pageWidth - '220'; 
     // apply the new width to the middle column 
     $('div.MiddleColumn').css('width', middleWidth); 
    }).resize(); 

}); 
相關問題