找了li 如何水平排列并自动填满 ul,同时 li 宽度平均?资料,里面有提到"请用js动态计算保证兼容性",
因为我想实现的是,水平滚动条,ul的上级div是固定的宽度1000px, 我就想到用jquery 获取每个li的高度,ul的宽度等于每个li的宽度.
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head > 4 <title>index.html</title> 5 <meta name="description" content="Hello world"> 6 7 <!-- jQuery 1.7.2+ or Zepto.js 1.0+ --> 8 <script src="http://ajax.useso.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 9 10 <style type="text/css"> 11 #category{ 12 width:1000px; 13 height:54px; 14 border:1px solid red; 15 overflow-x:auto; 16 overflow-y:hidden; 17 } 18 #category ul{ 19 margin:0px; 20 padding:0px; 21 list-style:none; 22 /**float:left;和overflow:hidden;是为了让ul的宽度为实际宽度,具体的区别,我还待学习**/ 23 overflow:hidden; 24 } 25 #category ul li{ 26 float:left; 27 margin:0px 10px; 28 padding:10px; 29 border:red; 30 } 31 32 </style> 33 34 </head> 35 <body> 36 <div id="category"> 37 <ul> 38 <li>Test</li> 39 <li>Test12321321</li> 40 <li>Test111</li> 41 <li>Test11</li> 42 <li>Test</li> 43 <li>Test</li> 44 <li>Test</li> 45 <li>Test</li> 46 <li>Test</li> 47 <li>Test</li> 48 <li>Test</li> 49 <li>Test</li> 50 <li>Test</li> 51 <li>Test</li> 52 </ul> 53 </div> 54 <script type="text/javascript"> 55 jQuery(function($){ 56 var ul_width = 0 ; 57 $("#category ul li").each(function(index,value){ 58 var width = $(value).width(); 59 //40是padding-left + padding-right + margin-left + margin-left 60 ul_width += (width + 40); 61 //console.log(width); 62 }); 63 $("#category ul").width(ul_width); 64 }); 65 66 </script> 67 </body> 68 </html>
最终的效果图是:
时间: 2024-10-20 06:33:53