[英]Total width of parent according to number of children
I want to add dynamic width in UL according to the its child. 我想根据其子级在UL中添加动态宽度。 Any idea how to do this using jQuery or Javascript?
知道如何使用jQuery或Javascript执行此操作吗?
<ul style="width:?">
<li style="width:50px;float:left;">&nbps;</li>
<li style="width:50px;float:left;">&nbps;</li>
<li style="width:50px;float:left;">&nbps;</li>
</ul>
$(function(){
$ul = $('#ul');
$ul.css('width',($ul.children().length*50)+"px");
alert($ul.css('width'));
});
http://jsfiddle.net/QctE3/ http://jsfiddle.net/QctE3/
And to adapt to changing widths: 并适应不断变化的宽度:
http://jsfiddle.net/QctE3/1/ http://jsfiddle.net/QctE3/1/
$(function(){
$ul = $('#ul');
cwidth = parseInt($ul.children('li:first-child').css('width'));
$ul.css('width',($ul.children().length*cwidth+"px"));
alert($ul.css('width'));
});
Try this: 尝试这个:
<script type="text/javascript" charset="utf-8">
var intTotalWidth = 0;
$("ul li").each(function(index, value) {
intTotalWidth = intTotalWidth + parseInt($(this).innerWidth());
});
$("ul").css("width", intTotalWidth);
</script>
list.style.width = list.childElementCount * 50 + 'px';
where list
is a reference to the UL element. 其中
list
是对UL元素的引用。
Btw, if you don't want to hard-code the width value ( 50
), you can read the width of the first LI element like so: 顺便说一句,如果您不想对宽度值(
50
)进行硬编码,则可以像这样读取第一个LI元素的宽度:
list.style.width =
list.childElementCount * list.firstElementChild.offsetWidth + 'px';
This code works in all current browsers, but not in IE8 and below. 该代码可在所有当前浏览器中使用,但不适用于IE8及以下版本。
Live demo: http://jsfiddle.net/simevidas/e77V4/1/ 现场演示: http : //jsfiddle.net/simevidas/e77V4/1/
If the LI elements have variable widths: 如果LI元素的宽度可变:
$('#list').width(function() {
var width = 0;
$(this).children().each(function() {
width += $(this).outerWidth();
});
return width;
});
Live demo: http://jsfiddle.net/simevidas/e77V4/2/ 现场演示: http : //jsfiddle.net/simevidas/e77V4/2/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.