2013-02-08 177 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

相关问题