2015-10-02 4 views
2

Итак, у меня есть несколько div с тем же классом и внутри них изображения, которые могут быть от 1 до 4 в зависимости от div, я не знаю заранее, сколько изображений, потому что они поступают из базы данных. Как я могу дать изображениям разные классы в зависимости от того, сколько их в div. MY HTMLотзывчивый макет изображения

<section class="feed-section"> 
    <article class="feed-article"> 
     <div class="question-options"> 
      <img src="http://placehold.it/600x400"> 
     </div> 
    </article> 
    <article class="feed-article"> 
     <div class="question-options"> 
      <img src="http://placehold.it/600x400"> 
      <img src="http://placehold.it/600x400"> 
      <img src="http://placehold.it/600x400"> 
      <img src="http://placehold.it/600x400"> 
     </div> 
    </article> 
    <article class="feed-article"> 
     <div class="question-options"> 
      <img src="http://placehold.it/600x400"> 
      <img src="http://placehold.it/600x400"> 
      <img src="http://placehold.it/600x400"> 
     </div> 
    </article> 
</section> 

мои JS

function imagesWidth() { 
    var imagesConatiner = $('.question-options').each(function (index) { 
     var images = $(this).children('img').length; 
     switch (images) { 
     case 1: 
      $('.question-options img').addClass('one') 
      break; 
     case 2: 
      $('.question-options img').addClass('two') 
      break; 
     case 3: 
      $('.question-options img').addClass('three') 
      break; 
     case 4: 
      $('.question-options img').addClass('four') 
      break; 
     default: 
      console.log(images) 
     } 
    }) 
}; 
imagesWidth() 

Сейчас проблема заключается в том, что это объявление несколько классов, например, для всех изображений, добавляет один для трех

Я хочу, чтобы сделать их с помощью CSS, как

img.one { 
    width:100% 
} 
img.two { 
    width:50% 
} 

И так далее ...

+1

Я по-прежнему получаю 2 или 3 класса на изображение, я хочу клас на div/изображение – user2991920

ответ

2

проблема заключается в том, что вы добавляете класс, поскольку вы получаете весь контейнер question-options. попробуйте это:

function imagesWidth() { 
    var imagesConatiner = $('.question-options').each(function (index) { 
     var images = $(this).children('img').length; 
     var self = $(this); 

     switch (images) { 
      case 1: 
       self.children('img').addClass('one') 
       break; 
      case 2: 
       self.children('img').addClass('two') 
       break; 
      case 3: 
       self.children('img').addClass('three') 
       break; 
      case 4: 
       self.children('img').addClass('four') 
       break; 
      default: 
       console.log(images) 
     } 
    }) 
}; 
imagesWidth() 

здесь является примером fiddle

0

Проблема с кодом является то, что вы используете общий селектор, чтобы добавить класс на изображениях. $('.question-options img') выберет все изображения внутри элемента, имеющего класс question-options. Вы можете использовать find, children с текущим контекстом ($(this)) или контекстный селектор, чтобы выбрать изображения, которые находятся внутри текущего элемента внутри each.

$('img', this).addClass('someclass'); 

Это добавит класс всех img элементов, находящихся внутри текущего элемента. то есть .question-options, на котором выполняется итерация.

Ваша проблема будет решена с использованием любого из приведенных выше способов.

Если вы ищете гибкую и оптимизированного раствор,

  1. Вы можете использовать массив с индексом в качестве количества изображений и значения как класс
  2. Добавьте класс на индекс всех изображений

// Create array for the classes, index will be treated as number of images and value is the class to add 
 
// Modify the array according to the maximum number of elements 
 
var classes = ['', 'one', 'two', 'three', 'four']; 
 

 
function imagesWidth() { 
 
    var imagesConatiner = $('.question-options').each(function(index) { 
 

 
    // Get the value from the array at the index i.e. no. of images and add it as class to all the images inside this container 
 
    $('img', this).addClass(classes[$(this).children('img').length]); 
 
    }) 
 
}; 
 
imagesWidth();
img.one { 
 
    width: 100% 
 
} 
 
img.two { 
 
    width: 50% 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> 
 
<section class="feed-section"> 
 
    <article class="feed-article"> 
 
    <div class="question-options"> 
 
     <img src="http://placehold.it/600x400"> 
 
    </div> 
 
    </article> 
 
    <article class="feed-article"> 
 
    <div class="question-options"> 
 
     <img src="http://placehold.it/600x400"> 
 
     <img src="http://placehold.it/600x400"> 
 
     <img src="http://placehold.it/600x400"> 
 
     <img src="http://placehold.it/600x400"> 
 
    </div> 
 
    </article> 
 
    <article class="feed-article"> 
 
    <div class="question-options"> 
 
     <img src="http://placehold.it/600x400"> 
 
     <img src="http://placehold.it/600x400"> 
 
     <img src="http://placehold.it/600x400"> 
 
    </div> 
 
    </article> 
 
</section>

0

У вас есть конкретная причина для добавления определенных классов на изображение? Вы могли бы добиться такого же эффекта (чтобы изображения были равномерно распределены по заданной ширине), используя чистый css flexbox и javascript.

.question-options { 
    display: flex; 
    width: 500px; 
    flex-direction: row; 
    padding: 10px; 
    background-color: blue; 
} 
.question-options div { 
    flex: 1 1 auto; 
} 
.question-options img { 
    width: 100%; 
} 

Вам однако нужно обернуть свои изображения в DIV, чтобы сделать его работу:

<section class="feed-section"> 
    <article class="feed-article"> 
    <div class="question-options"> 
     <div><img src="http://placehold.it/600x400"></div> 
    </div> 
    </article> 
    <article class="feed-article"> 
    <div class="question-options"> 
     <div><img src="http://placehold.it/600x400"></div> 
     <div><img src="http://placehold.it/600x400"></div> 
     <div><img src="http://placehold.it/600x400"></div> 
     <div><img src="http://placehold.it/600x400"></div> 
    </div> 
    </article> 
    <article class="feed-article"> 
    <div class="question-options"> 
     <div><img src="http://placehold.it/600x400"></div> 
     <div><img src="http://placehold.it/600x400"></div> 
     <div><img src="http://placehold.it/600x400"></div> 
    </div> 
    </article> 
</section> 

Fiddle: https://jsfiddle.net/grxp0gw1/

NB: Flexbox не (пока) играть хорошо с изображениями. Благодаря this post и this fiddle Мне удалось заставить его работать.

+0

Интересно, можете ли вы создать рабочую демонстрацию – Tushar

+0

(обновленный ответ со ссылками на дополнительную помощь по выполнению этой работы с помощью css) – wintvelt

+0

Это не что OP хочет, OP хочет, если есть несколько изображений, которые они должны быть сведены к минимуму, чтобы показать все изображения в контейнере. – Tushar

1

Ваш код должен быть таким:

function imagesWidth() { 
    var imagesConatiner = $('.question-options').each(function (index) { 
     var images = $(this).children('img').length; 
     switch (images) { 
     case 1: 
      $(this).find('img').addClass('one') 
      break; 
     case 2: 
      $(this).find('img').addClass('two') 
      break; 
     case 3: 
      $(this).find('img').addClass('three') 
      break; 
     case 4: 
      $(this).find('img').addClass('four') 
      break; 
     default: 
      console.log(images) 
     } 
    }) 
}; 
imagesWidth() 

Вы не были ссылки на родительский DIV, как «это» так было добавление классов к ребенку все».question опционы метки„IMG“.

Смежные вопросы