Interested to know if I can use jQuery to find the first image on the page and display it inside a resized to a thumbnail with click to enlarge. For example, on this particular blog, when the client adds an image to the post, jQuery will find the first image, display it as a clickable thumbnail in a particular location. 开发者_JAVA技巧It would be ideal if the detailed image could display in thickbox, facebox or another jQuery overlay window.
Thanks in advance for your ideas. Jackson
You can use the :first
selector to find the first image, then using cloning you can copy the image to any other location and modify it from there.
$(document).ready(function() {
var firstImage = $('img:first');
var link = $('<a />')
.attr('href', '#')
.append($('img:first').clone().css({ width:100, height:100 }))
.append($('<div />').text('Click to Enlarge'))
.click(function(e) {
e.preventDefault();
// showDialog();
});
$('.imageThumbnail').append(link);
$('.imageDialog').append(firstImage.clone());
});
To find the first image in your page you can use the :first selector.
$("img:first")
will select the first img element.
If you want to restrict the search within a parent element then you can
$("#parentElemId").find("img:first")
If you can give these image elements a class name then you can do
$("img.classname:first")
Like other members have mentioned you can get the first image by using img:first. The simplest way to display it as a thumbnail would be:
$(document).append("<img src='" + $("img:first").attr("src") + "' alt='' class='thickbox' style='width: 50px; height: 50px;' />");
The class='thickbox'
part is for the thickbox plugin
Here's a more specific sample based on your comment:
If the original data looks something like this:
<div id="thumbs"></div>
<div id="article">
<img src="..." alt="" />
Some text..
</div>
You can use something like this:
var images = "";
$("#article img:first").each(function() {
images += "<img src='" + $(this).attr('src') + "' width='45' class='thickbox' alt='Click to enlarge' /> ";
});
$("#thumbs").append(images);
精彩评论