how to display an image inside <img> tag always in full dimension
I've an img elem开发者_JS百科ent with dynamically changing image. I always want to show this image in its full dimension.
So, I think, I've to dynamically change width and height attributes in img tag.
How can I do this in php or javascript?
Just leaving off the width and height attributes (and styles) should do. If you need to know it afterwards you can grab it from the computed CSS.
Couldn't you do without the width and height dimensions? As far as I've seen if you don't define the width and height the browser displays the entire full size image. Most modern browsers that is.
Assuming that you care about alt, height, and width attributes (you should), reading the image properties from a javascript array may be a good fit for you. Here's an example in jQuery inserting a random image, you could swap the random image logic out for any kind of slideshow, etc that you'd like for rendering.
$(document).ready(function() {
var imageArray = new Array ();
imageArray[0] = new Array ( "jungle.jpg", "http://rmportal.net", "Jungle", "400", "300");
imageArray[1] = new Array ( "mountain.jpg", "http://rmportal.net", "Mountain" , "350", "290");
imageArray[2] = new Array ( "ocean.jpg", "http://rmportal.net", "Ocean" , "442", "530");
var max = imageArray.length;
var num = Math.floor((Math.random() * max));
var hstring = "<a href='" + imageArray[num][1] + "'><img src='" + imageArray[num][0] + "' alt='" + imageArray[num][2] + "' height='" imageArray[num][3] + "' width='" + imageArray[num][4] + "' /></a>"
$('#my-image').html(hstring);
});
If you’d prefer to keep the width
and height
attributes in your HTML, then in PHP you want the getimagesize
method in the GD library.
If the page loads with the image’s width and height included as attributes in the source,
use removeAttribute('width')
and 'height'
the first time you change its source.
If you don’t want the page to ‘collapse’ during a slow download, preload the image and change the src after img.complete
is true, which is right away if it is cached, or after the image onload fires.
精彩评论