Set image width to span tag
I have this html code
<ul>
<li><a href="#"><img src="path_to_image1"><span>some text</span></a></li>
<li><a href="#"><img src="path_to_image2"><span>some text</span></a></li>
<li><a href="#"><img src="path_to_image3"><span>some text</span></a></li>
</ul>
开发者_如何学编程
Images are of different width.
I need to set width of SPAN element to be equal as IMG width. Here is the code that I wrote by looking over the StackOverflow board.
$(document).ready(function() {
$("ul li a").each(function() {
var theWidth = $(this).find("img").width();
$("ul li a span").width(theWidth);
});
});
Now this code returns only width of the last image. What to change so I can have width of span element same as img?
Thanks
$('ul li img').each(function() {
var imgWidth = $(this).width();
$(this).next('span').css({'width': imgWidth});
});
You just need to correct one line:
$("ul li a span").width(theWidth);
Replace with:
$(this).find('span').width(theWidth);
the answer is in your own code, almost..
$(this).find("span").width(theWidth);
Replace this line
$("ul li a span").width(theWidth);
with
$(this).find('span').width(theWidth);
Explanation: the line $("ul li a span").width(theWidth);
sets the width for all three span
elements.
The 'each' loop runs 3 times.
The first time it sets all three spans to the width of the first image.
The second time it sets all three spans to the width of the second image.
...
Can you just set the widths of the <li>
's to the same width as the image and set the <span>
as display: block
;
The spans will then be as wide as their contain (the <li>
) and it saves you a little extra jquery trying to dig down to span level.
Also, to help speed up your jquery selector simply add an id to the list and target that instead of trying to match ul li a...
; now all you have to do is match #widths
.
Example
<ul id="widths">
<li><a href="#"><img src="path_to_image1"><span>some text</span></a></li>
<li><a href="#"><img src="path_to_image2"><span>some text</span></a></li>
<li><a href="#"><img src="path_to_image3"><span>some text</span></a></li>
</ul>
$(document).ready(function() {
$('#widths img').each(function() {
var imgWidth = $(this).width();
$(this).next('span').css({'width': imgWidth});
});
});
There are many ways around this, this worked for me though.
$(document).ready(function () {
$("ul li a img").each(function (index) {
$(this).next().width($(this).width()).css("display", "block");
});
});
精彩评论