添加不同的 类 到 VERTICAL 或 HORIZONTAL img

Add different classes to VERTICAL or HORIZONTAL img

如果图像是垂直的或垂直的,我想设置不同的样式。

我正在研究这段代码,但它不起作用。有什么想法吗?

JAVASCRIPT

(function() {

var orientation,
img = new Image();

img.onload = function () {

if (img.naturalWidth > img.naturalHeight) {
$(img).addClass('landscape');} 

else (img.naturalWidth < img.naturalHeight) {
$(img).addClass('portrait');} 

})();

CSS

img {max-width:500px;}
.landscape {max-width: 750px;}
.portrait {max-width: 500px;}

我刚刚在这里创建了一个简短的代码笔来向您展示我处理图像的方式: codepen link

HTML:

<img src="https://pixabay.com/static/uploads/photo/2014/07/27/20/29/landscape-403165_960_720.jpg" />

<img src="https://s-media-cache-ak0.pinimg.com/736x/f5/a0/62/f5a0626a80fe6026c0ac65cdc2d8ede2.jpg" />

CSS:

.landscape {max-width: 750px;}
.portrait {max-width: 500px;}

JS:

window.onload = function () {
  var images = document.getElementsByTagName('img');

  for( var i=0; i<images.length;i++){
    if (images[i].naturalWidth > images[i].naturalHeight) {
      $(images[i]).addClass('landscape');
    } 
    else{ 
      if(images[i].naturalWidth < images[i].naturalHeight) {
        $(images[i]).addClass('portrait');  
      }
    }
  }
}

您不能将条件与 if-else 语句的 else 部分一起使用。使用以下代码结构:

img.onload = function () {
  if (condition) {
     // if above condition is true then do this ...
  } else {
    // otherwise do this ...
  }
});

var images = $('.img img');

images.load(function() {
  if (this.naturalWidth > this.naturalHeight) {
    $(this).addClass('landscape');
  } else {
    $(this).addClass('portrait');}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="img">
  <img src="http://www.w3schools.com/html/pic_mountain.jpg" alt="Image Description">
</div>