JS: пытается создать повторяющуюся функцию, которая увеличивает и уменьшает изображение

Другое решение flexbox

Вы можете использовать инверсию порядка элементов в HTML. Затем, используя order, как в ответе Michael_B , вы можете использовать flex-direction: row-reverse; или flex-direction: column-reverse; в зависимости от вашего макета.

Рабочий пример:

.flex {
  display: flex;
  flex-direction: row-reverse;
   /* Align content at the "reversed" end i.e. beginning */
  justify-content: flex-end;
}

/* On hover target its "previous" elements */
.flex-item:hover ~ .flex-item {
  background-color: lime;
}

/* styles just for demo */
.flex-item {
  background-color: orange;
  color: white;
  padding: 20px;
  font-size: 3rem;
  border-radius: 50%;
}
5
4
3
2
1

2
задан John Nada 15 January 2019 в 20:21
поделиться

2 ответа

Так как вам нужно вызвать foo с true или false, я думаю, вы можете предпочесть рекурсивное setTimeout, чем setInterval:

function foo(toggle) {
  const img = document.querySelector('.product-image');
  img.style.width = img.style.width || "0px";
  const currentWidth = parseInt(img.style.width.match(/\d+/g)[0])
  const newWidth = toggle 
    ? currentWidth + 50 
    : currentWidth - 50;
  img.style.width = newWidth.toString() + "px"
  img.style.transition = "all 2s"
  setTimeout(foo.bind(null, !toggle), 1000);
}

foo(false)
[ 111]

0
ответ дан antonku 15 January 2019 в 20:21
поделиться
  1. Сделайте toggle глобальной переменной,
  2. Для производительности сделайте img глобальной,
  3. Установите переход на элемент только один раз .

Таким образом:

function foo() {
  if (img.style.width == "") {
    img.style.width = "0px";
  }

  let width = parseInt(img.style.width.match(/\d+/g)[0]);

  if (toggle) {
    width -= 50;
  }
  else {
    width += 50;
  }

  img.style.width = width + "px";

  toggle = !toggle;

}

const img = document.querySelector('.product-image');
let toggle = true;

img.style.transition = "all 2s";

let interval = setInterval(foo, 1000);
0
ответ дан do or do not 15 January 2019 в 20:21
поделиться
Другие вопросы по тегам:

Похожие вопросы: