jquery实现tag平均宽度
jquery
function widget_tags(tt) { var $it = tt.find($('li')); var mw = tt.width(); var index = 0; var t = 0; $it.each(function() { var $c = $(this); var ow = $c.outerWidth(true); var bw = ow - $c.outerWidth(); t += ow; if (t > mw) { var $pt = $c.prev(); var p = mw - (t - ow); aw($pt, p + bw); t = ow; } if ($c.is(':last-child')) { var p = mw - t; aw($c, p + bw); } }); function aw($pt, adw) { var r = ranges(index, $pt.index()); var d = Math.floor(adw / r.length); var e = adw % r.length; for (var i in r) { var $im = $it.eq(r[i]); $im.width($im.width() + d); } $pt.width($pt.width() + e); $pt.css('margin-right', 0); index = $pt.index() + 1; }; function ranges(l, h, s) { var mx = []; var i, e, p; var wr = s || 1; var cs = false; if (!isNaN(l) && !isNaN(h)) { i = l; e = h } else if (isNaN(l) && isNaN(h)) { cs = true; i = l.charCodeAt(0); e = h.charCodeAt(0) } else { i = (isNaN(l) ? 0 : l); e = (isNaN(h) ? 0 : h) } p = ((i > e) ? false: true); if (p) { while (i <= e) { var cc = String.fromCharCode(i); mx.push(((cs) ? cc: i)); i += wr } } else { while (i >= e) { var cc = String.fromCharCode(i); mx.push(((cs) ? cc: i)); i -= wr } } return mx; } };
使用
html
<ul class="amz-widget-tags am-cf"> <li class="am-badge"><a href="#">jquery</a></li> <li class="am-badge"><a href="#">标签</a></li> <li class="am-badge"><a href="#">分页</a></li> <li class="am-badge"><a href="#">tags</a></li> <li class="am-badge"><a href="#">编辑器</a></li> <li class="am-badge"><a href="#">destoon</a></li> <li class="am-badge"><a href="#">poscms</a></li> <li class="am-badge"><a href="#">图片</a></li> <li class="am-badge"><a href="#">百度</a></li> <li class="am-badge"><a href="#">调用</a></li> </ul>jquery
$(function(){ widget_tags($('.amz-widget-tags')); // 窗口大小改变是重新执行,自适应页面适用。 $(window).resize(function(){ if($(".amz-sidebar").css('display')!='none'){ //判断ul的上级元素是否显示,改成自己的就好 $('.amz-widget-tags').find('li').attr('style',''); widget_tags($('.amz-widget-tags')); } }); });css
.amz-widget-tags li { float: left;margin-top: 5px;margin-right: 6px;} .amz-widget-tags a {color: #fff;font-size: 1.5rem;font-weight: normal;} .am-badge{display:inline-block;min-width:10px;padding:0.25em 0.625em;font-size:1.2rem;font-weight:bold;color:#fff;line-height:1;vertical-align:baseline;white-space:nowrap;text-align:center;background-color:#999999;border-radius:0;}
随机颜色在后面会分享