admin管理员组

文章数量:1300164

I've an img element 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?

I've an img element 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?

Share asked Mar 14, 2010 at 20:37 understackunderstack 11.6k24 gold badges79 silver badges100 bronze badges
 | 

5 Answers 5

Reset to default 11

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 puted 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", "Jungle", "400", "300");
  imageArray[1] = new Array ( "mountain.jpg", "http://rmportal", "Mountain" , "350", "290");
  imageArray[2] = new Array ( "ocean.jpg",    "http://rmportal", "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.plete is true, which is right away if it is cached, or after the image onload fires.

本文标签: phphow to display an image inside ltimggt tag always in full dimensionStack Overflow