CSS: high-altitude auto issue in flexible layout

I am using jquery lazy load in a flexible layout with an empty gif as a preview. To get a lazy load, I have to set the height and width of the image by attributes.

The preview image is not set to the correct height, since height: auto apparently calculates the height using src not using the height attribute. I always get a square.

Here is an example:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Test</title>
  <style type="text/css">
    img {
      background-color: #000;
      max-width: 100%;
      height: auto;
    }
  </style>
</head>
<body>
  <img src="blank.gif" width="500" height="300">
</body>
</html>

Any ideas for this?

+5
source share
3 answers

There is no fixed correct height. If I set a fixed height in css, the image will not change with the correct aspect ratio in my responsive layout.

, css , src, width- height. , , . ( 1x1), , , html, css ( css -).

, , "height: auto" " " " " jquery :

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Test</title>
  <style type="text/css">
    img {
      max-width: 100%;
    }
    .lazy-loaded {
      height: auto;
    }
  </style>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
  <script language="JavaScript">
    $(document).ready(function(){
      resizeBlankImages();
    });
    $(window).resize(function(){
      resizeBlankImages();
    });
    function resizeBlankImages() {
      $(".lazy-blank").each(function () {
        var originalWidth = $(this).attr('width');
        var originalHeight = $(this).attr('height');
        var ratio = originalWidth/originalHeight;
        var width = $(this).width();
        var height = width/ratio;
        $(this).height(height);
      });
    }
  </script>
</head>
<body>
  <img data-original="image.jpg" src="image.jpg" class="lazy lazy-loaded" width="500" height="300">
  <br/>
  <img data-original="image.jpg" src="blank.gif" class="lazy lazy-blank" width="500" height="300">
</body>
</html>

, . ?

+1

? 500 x 300 , CSS.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Test</title>
  <style type="text/css">
    img {
      background-color: #000;
      max-width: 100%;
      width: 300px;
      height: 500px;
    }
  </style>
</head>
<body>
  <img src="blank.gif" alt="preview" />
</body>
</html>
0

Add a .load event handler to your lazy images. When they load, we add the .lazy_loaded class

$("img.lazy").lazyload().load(function() {
    var self = $(this);
    if(self.attr('src') == self.data('original')){
        self.addClass('lazy_loaded');
    }
});

Then in your css apply only height: auto; rule for .lazy_loaded

.img.lazy{
    max-width: 100%;
}
img.lazy_loaded{
    height: auto;
}
0
source

All Articles