向VERTICAL或HORIZONTAL img添加不同的类 [英] Add different classes to VERTICAL or HORIZONTAL img

查看:126
本文介绍了向VERTICAL或HORIZONTAL img添加不同的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果图像是垂直的或水平的,我想用不同的样式.

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

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,向您展示了我处理图像的方式: codepen链接

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

这篇关于向VERTICAL或HORIZONTAL img添加不同的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆