Is it possible to get width of multiple <span> elements?
So I have a c开发者_开发知识库ouple of <span>
elements that are being generated dynamically. The thing is that I need to know their width together. I tried to wrap them with <div>
and made alert($("#spanWrap").width());
but it gave width of container instead of <span>
elements.
I think I can try to explain it best by jsFiddl'n it here: http://jsfiddle.net/XGynv/7/
add display: inline-block;
to the style of your div wrapping the spans.
edit:
with the spans wrapped in a div as in
<div id="spanwrapper">
<span>span1</span>
<span>span2</span>
</div>
the css style should contain (in this order, see comments by gilly3):
#spanwrapper {
display: inline-block; // the div shrinks to fit around the content
}
#spanwrapper {
*display: inline; // adding support for IE7 or lower
}
so that you get the width using jquery:
$("#spanwrapper").width();
or using conventional javascript:
document.getElementById('spanwrapper').clientWidth;
note that with the size defined by the browser, it now does not make sense to define a fixed width in the style.
There is no way you can do it unless you write your own code to add up width of each span like below.
var w = 0;
$("#divMenuSpan span").each(function(){
w += $(this).width();
});
//Now w will have the combined width of all the spans inside divMenuSpan
It's an obvious answer but you could just do -
parseInt($("#fashion").width()) + parseInt($("#wedding").width())
Might be easier if you just changed that container to a span instead of a div
<span id="divMenuSpan">
http://jsfiddle.net/XGynv/8/
I updated your jsFiddle.
Basically I am looping through the spans and summing the widths.
That is because a div is a block element and block elements always fill the width of their container. To make a div fit the width of its contents, float it:
http://jsfiddle.net/XGynv/12/
#wrap
{
width: 666px;
overflow: hidden;
}
#divMenuSpan
{
float: left;
}
Edit: I should point out that if your spans wrap, the width of the floated container div will shrink using this technique. If you want the actual width of the spans, you'd have to iterate the divs in a loop and add up the sum of their widths.
Something like
var size = 0;
$('span.someclass').each(function(el) { size += $(el).width(); });
?
You can write javascript codes to calculate it.
$(document).ready(function() {
var spans = $("span"), //span collection
width = 0;
spans.each(function(index,ele){
width = width + $(ele).outerWidth(true); //here, it will include margin.
});
console.log(width);
});
精彩评论