Есть ли более оптимальный способ изменить несколько классов и идентификаторов с javascript, чем этот? - PullRequest
0 голосов
/ 04 марта 2020

Я создаю функцию настройки еды на веб-сайте, где клиент может выбирать различные ингредиенты для настройки своей еды. У меня отлично работает задняя часть, но у меня немного проблемы с передним концом.

Я использовал различные идентификаторы, классы и функции для создания наложения при наведении курсора и затем накладывал границу вокруг изображений продуктов, как только они были нажаты (выбраны), но это довольно длинный метод. Это работает, но поскольку ингредиентов намного больше, чем этот (еще 30), я немного беспокоюсь о том, что функции становятся слишком длинными.

HTML

image

CSS:

#food:hover, #food1:hover, #food2:hover, #food3:hover, #food4:hover, #food5:hover, #food6:hover, #food7:hover{
    filter: brightness(75%); !important;
}

.selected {
  border: 3px solid #186472 !important;
}

JavaScript

<script>
function select(){
    document.getElementById("food").classList.add('selected');
    document.getElementById("food1").classList.remove('selected');
    document.getElementById("food2").classList.remove('selected');
    document.getElementById("food3").classList.remove('selected');
    document.getElementById("food4").classList.remove('selected');
    document.getElementById("food5").classList.remove('selected');
    document.getElementById("food6").classList.remove('selected');
    document.getElementById("food7").classList.remove('selected');
}

function select1(){
    document.getElementById("food").classList.remove('selected');
    document.getElementById("food1").classList.add('selected');
    document.getElementById("food2").classList.remove('selected');
    document.getElementById("food3").classList.remove('selected');
    document.getElementById("food4").classList.remove('selected');
    document.getElementById("food5").classList.remove('selected');
    document.getElementById("food6").classList.remove('selected');
    document.getElementById("food7").classList.remove('selected');
}

function select2(){
    document.getElementById("food").classList.remove('selected');
    document.getElementById("food1").classList.remove('selected');
    document.getElementById("food2").classList.add('selected');
    document.getElementById("food3").classList.remove('selected');
    document.getElementById("food4").classList.remove('selected');
    document.getElementById("food5").classList.remove('selected');
    document.getElementById("food6").classList.remove('selected');
    document.getElementById("food7").classList.remove('selected');
}

function select3(){
    document.getElementById("food").classList.remove('selected');
    document.getElementById("food1").classList.remove('selected');
    document.getElementById("food2").classList.remove('selected');
    document.getElementById("food3").classList.add('selected');
    document.getElementById("food4").classList.remove('selected');
    document.getElementById("food5").classList.remove('selected');
    document.getElementById("food6").classList.remove('selected');
    document.getElementById("food7").classList.remove('selected');
}

function select4(){
    document.getElementById("food").classList.remove('selected');
    document.getElementById("food1").classList.remove('selected');
    document.getElementById("food2").classList.remove('selected');
    document.getElementById("food3").classList.remove('selected');
    document.getElementById("food4").classList.add('selected');
    document.getElementById("food5").classList.remove('selected');
    document.getElementById("food6").classList.remove('selected');
    document.getElementById("food7").classList.remove('selected');
}

function select5(){
    document.getElementById("food").classList.remove('selected');
    document.getElementById("food1").classList.remove('selected');
    document.getElementById("food2").classList.remove('selected');
    document.getElementById("food3").classList.remove('selected');
    document.getElementById("food4").classList.remove('selected');
    document.getElementById("food5").classList.add('selected');
    document.getElementById("food6").classList.remove('selected');
    document.getElementById("food7").classList.remove('selected');
}

function select6(){
    document.getElementById("food").classList.remove('selected');
    document.getElementById("food1").classList.remove('selected');
    document.getElementById("food2").classList.remove('selected');
    document.getElementById("food3").classList.remove('selected');
    document.getElementById("food4").classList.remove('selected');
    document.getElementById("food5").classList.remove('selected');
    document.getElementById("food6").classList.add('selected');
    document.getElementById("food7").classList.remove('selected');
}

function select7(){
    document.getElementById("food").classList.remove('selected');
    document.getElementById("food1").classList.remove('selected');
    document.getElementById("food2").classList.remove('selected');
    document.getElementById("food3").classList.remove('selected');
    document.getElementById("food4").classList.remove('selected');
    document.getElementById("food5").classList.remove('selected');
    document.getElementById("food6").classList.remove('selected');
    document.getElementById("food7").classList.add('selected');
}
</script>

Пример изображения

Ответы [ 5 ]

1 голос
/ 04 марта 2020

Если вы просите пользователей выбрать элементы из ряда вещей, вам следует рассмотреть возможность использования переключателей. Использование переключателей облегчит задачу с точки зрения кода, избавив от необходимости устанавливать выбранное состояние с помощью javascript, и оно станет более доступным для пользователей.

Вот один из способов приблизиться к этому с нет javascript необходимо , с использованием :checked CSS псевдокласс и CSS соседний братский комбинатор (+) для добавления красного границы для проверенных продуктов питания.

.food {
  display: inline-block;
}
.food input {
  visibility: hidden;
}
.food img {
  border: 5px solid white;
}
.food input:checked + label img {
  border: 5px solid red;
}
.food input:not(:checked) + label {
  cursor: pointer;
}
.food input:not(:checked) + label:hover img {
  opacity: 0.75;
}
<div class="food">
  <input type="radio" id="food1" name="food" value="food1" />
  <label for="food1"><img alt="food1" src="https://placehold.it/100/100/?text=food1"/></label>
</div>
<div class="food">
  <input type="radio" id="food2" name="food" value="food2" />
  <label for="food2"><img alt="food2" src="https://placehold.it/100/100/?text=food2"/></label>
</div>
<div class="food">
  <input type="radio" id="food3" name="food" value="food3" />
  <label for="food3"><img alt="food3" src="https://placehold.it/100/100/?text=food3"/></label>
</div>
0 голосов
/ 04 марта 2020

Читать JS комментарии:

window.onload = function() {
  var foods = document.getElementsByClassName('food'); // To get length of all food pictures.
        for(var i = 0; i < foods.length; i++) { // for loop to create click function on each image.
            var food = foods[i]; // get current class index.
            food.onclick = function() { // DOM onclick function.
                Array.from(foods).forEach(function(e){e.classList.remove('selected')}) // remove 'selected' class from all 'food' classes. 
                this.classList.add('selected'); // add selected class to current '.food'.
            }
        }
    }
.food:hover {
    filter: brightness(75%); !important;
}

.selected {
  border: 3px solid #186472 !important;
}
<img class="food" src="https://picsum.photos/200">

<img class="food" src="https://picsum.photos/200">

<img class="food" src="https://picsum.photos/200">

<img class="food" src="https://picsum.photos/200">

<img class="food" src="https://picsum.photos/200">

<img class="food" src="https://picsum.photos/200">

<img class="food" src="https://picsum.photos/200">

<img class="food" src="https://picsum.photos/200">

<img class="food" src="https://picsum.photos/200">
0 голосов
/ 04 марта 2020

Используйте классы, такие как селектор:

image

JavaScript будет выглядеть так:

<script>
$food_els = document.getElementByClassName("food");
function select(e) {
    for (var i = 0; i < $food_els.length; i++) {
        if ($food_els[i] == e) {
            $food_els[i].classList.add("selected");
        }
        else {
            $food_els[i].classList.remove("selected");
        }
    }
}
</script>
0 голосов
/ 04 марта 2020

Вы должны использовать
- лучше CSS
- div для групповых изображений
- делегирование событий

HTML

<div id="Group-Images">
  <img id="food1" src="Curried-Chicken-Breast-1-scaled.jpg" >
  <img id="food2" src="Curried-Chicken-Breast-2-scaled.jpg" >
  <img id="food3" src="Curried-Chicken-Breast-3-scaled.jpg" >
</div>

CSS

#Group-Images > img {
  width: 250px;
}
#Group-Images > img:hover {
  filter: brightness(75%) !important;
}
#Group-Images > img.selected {
  border: 3px solid #186472 !important;
}

JS

const GroupImages = document.getElementById('Group-Images')
  ,   AllImages   = GroupImages.querySelectorAll('img')
  ;
GroupImages.onclick=e=>
  {
  if (!e.target.matches('img')) return

  // console.log( e.target.id) // --> food1, food2,... foodN

  AllImages.forEach(imh=>
    {
    if (img===e.target) { img.classList.add('selected')   }
    else                { img.classList.remove('selected') }
    })
  }
0 голосов
/ 04 марта 2020

Вы всегда можете сделать это как функцию.

function select( val ){

    for (let i = 0; i < 7; ++i){
        document.getElementById(`food${i}`).classList.remove('selected');
    } 

    document.getElementById(`food${val}`).classList.add('selected');
}

// select(1)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...