2011-01-24 56 views

回答

2

试试这个(需要情况下护理的时候有没有孩子富):

var el = $('#foo'); 
var len = el.children().length; 
if(len > 0){ 
    len = 100/len; 
    el.css("width", len + "px"); 
} 
+0

赞一个最好的,因为它占了一个固定宽度容器通常是比基于%更好。 +1为改善我的概念! – Brian 2011-01-25 01:33:30

1
var count = $('#foo > *').length; 
$('#bar').css({width:(100/count)+'%'}); 
3
$('someelement').width((100/$('#foo').find('li').length)); 

你应该做一个检查,如果.length是零,零,以避免分裂。

0
<html> 
<head> 
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.4.min.js" 
type="text/javascript"></script> 
</head> 
<body> 
    <div id="foo"> 
     <ul> 
      <li>Baseball</li> 
      <li>Basketball</li> 
      <li>Football</li> 
      <li>Soccer</li> 
      <li>Hockey</li> 
     </ul> 
    </div> 
    <script type="text/javascript"> 
     $(function() { 
      var sWidth = "auto"; 
      var liLength = $("#foo li").length; 
      alert(liLength); 
      if (liLength > 0) { 
       sWidth = (100/liLength) + "%"; 
      } 
      $("#foo").width(sWidth); 
      alert(sWidth); 
     }); 
    </script> 
</body> 
</html>