Lets say I have the following html:
<div id="container">
<img id="large-image" src="/img/large-image.jpg" />
<img id="large-image-thumb" src="/img/large-image-thumb.jpg" />
</div>
How can i make it so that the thumbnail is sized the same way as the image? Is there a better way to structure this?
The function of this is to provide a low-quality version of an image while the full-quality version is loading, where the low-quality version has already been loaded (thus progressive jpgs are not helpful). This is used to display a large image when a thumbnail in a gallery is clicked.
Oh, and I know the width and the height of the large image befo开发者_开发技巧re it has loaded, but I would rather not set an explicit size within the javascript if possible- it should scale when the user resizes the window if possible. Catching the resize()
event just feels dirty.
An ancient (but still valid) technique is to use the LOWSRC attirbute of the IMG tag. This was once used back in the dial-up days when images did take a long time to download. People used it for low-resolution + low palette versions to load quickly while the full version loaded after.
<img src="... big image ..." lowsrc="... same size but small file image ..." />
With jQuery you can do
var largew = $('#container').find('img').eq(1).width(),
largeh = $('#container').find('img').eq(1).height();
$('#container').find('img').eq(0).css({
height: largeh,
width: largew
});
The thumb image will be sized the same as the large image. eq(0)
is referencing the first image which is the thumb and eq(1)
is referencing the second image which is the large one. This is assuming that you have them in this order inside #container
. Also you should use class instead of id for your images. That is if you are planning to use the same id names on other images. You can only use an id once in your HTML unlike class where it can applied to many number of HTML elements.
Check working example http://jsfiddle.net/7j7kJ/
I´m a bit confused by the last part of the question: if the image is scaled relative to the browser window, you can do the same for the large and the small image; just set the height or the width to 100% (for example) using css.
You can even load the big image using javascript and have it replace the small image when it is loaded, that way you can program it after the initial page-load to insure that your small images get loaded first.
In jQuery, you can start loading the large images when the whole "normal" page has loaded, using:
$(window).load(function() {
large_image = new Image();
large_image.src = "/img/large-image.jpg";
// etc.
// replace the source of the small image with the big image
// you will need some additional code to check for the load event of the large images
});
精彩评论