Вопрос

Here's my problem, I have a portfolio where images appear dynamically :

<?php echo'<div class="real"><img src='".$pathReal."'></div>' ?>

They must resize in rapport by the size of the image.

So, in jQuery, I assign a class in rapport by the size of the image :

$(".real img").each(function(){
  var widthImage = $(this).width();
  var heightImage = $(this).height();

  if(widthImage > heightImage ){
     $(".real img").addClass('realHeight');
  }else{
     $(".real img").addClass('realWidth');
  }
});

But it's not working :

<img class="realHeight realWidth" src="img/1.jpg">

2 class are applied, when I want it to be one or the other.

(CSS):

.realWidth{width: 100%;}

.realHeight{height: 100%;}

Can someone help me, please ?

(sorry for my bad english)

Это было полезно?

Решение

Use $(this) in your loop to manipulate the right DOM Element (your image tag)

And use naturalWidth and naturalHeight to get the correct size of the image.

$(".real img").each(function(){
  var widthImage = $(this).naturalWidth;
  var heightImage = $(this).naturalHeight;

  if(widthImage > heightImage ){
     $(this).addClass('realHeight');
  }else{
     $(this).addClass('realWidth');
  }
});

Другие советы

Your echo seems to be wrong:

<?php echo'<div class="real"><img src='".$pathReal."'></div>' ?>

which should be like this:

<?php echo'<div class="real"><img src="'.$pathReal.'"></div>' ?>

Ans as you are looping so you can use $(this)

if(widthImage > heightImage ){
   $(this).addClass('realHeight');
}else{
   $(this).addClass('realWidth');
}

Use this instead of applying the class selectors inside each

$(".real img").each(function(){
  var widthImage = $(this).width();
  var heightImage = $(this).height();

  if(widthImage > heightImage ){
     $(this).addClass('realHeight');
  }else{
     $(this).addClass('realWidth');
  }
});

$(".real img").addClass('realHeight');

This will apply realHeight class to all the images with class real. We dont want that

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top