2013-02-08 175 views
1

我希望有人可以幫助。jquery計算元素大小,同時調整窗口大小

我已經寫了一個函數,它根據現有列表項的數量和父容器中的剩餘寬度將寬度添加到導航欄中的最後一個li項。

這對文檔加載效果很好,如果文檔調整大小並單擊href,但在實際調整大小時不會重新計算元素的大小。

我製作了fiddle來幫助說明這一點。

有誰知道如何在窗口大小調整時動態地進行計算嗎?

這是JS

$(document).ready(calcWidth); 
$(document).resize(calcWidth); 

function calcWidth(){ 
    // get array of all the list items in the nav 
    var $listWidth = $('ul#main-nav li').map(function(){ 
     return $(this).width(); 
    }).get(); 
    var $itemCount = $('#main-nav li').length; //this works as margin-right is set to 1px 
    var $contWidth = $('#main-nav').width(); // get the full container width 
    var $sum = 0; 
    $.each($listWidth,function(){$sum+=parseFloat(this) || 0;}); 
    $('ul#main-nav li.final a').css({ 
     width: $contWidth - $sum - $itemCount, //set the width of the final li to be the total container minus the sum of the existing li elements 
     height: '12px' 
    }); 
} 

如果您需要貼在這裏更多的代碼,讓我知道,但是這一切都在撥弄。

感謝 盧克

+0

我一直在努力做到這一點,不介意知道這個祕密。 – lharby 2013-02-08 13:01:16

回答

2

你不需要用JavaScript來做到這一點。

在UL上移動clearfix類(因爲列表項是浮動的),在UL上添加紫色背景,並在列表項上添加1px白色右邊框。你可以刪除最後一個LI。

See it here

+0

謝謝。我把你的小提琴撥開了! – lharby 2013-02-08 14:21:54

相關問題