简体   繁体   中英

how to display an image inside <img> tag always in full dimension

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?

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);

});

如果您希望在HTML中保留widthheight属性,那么在PHP中您需要GD库中的getimagesize方法。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM