Add different classes to VERTICAL or HORIZONTAL img

女生的网名这么多〃 提交于 2019-12-13 03:38:18

问题


I want to style differently the images if they are vertical or hotizontal.

I'm playing around with this code but it's not working. Any ideas?

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

回答1:


I've just created short codepen here to show you my way of working with images: 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');  
      }
    }
  }
}



回答2:


You cannot use condition with else part of if-else statement. Use the following code structure:

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>


来源:https://stackoverflow.com/questions/38430194/add-different-classes-to-vertical-or-horizontal-img

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!