0

Всем привет! Сделал слайдер , но не могу понять как сделать его цикличным. Код js:

const entities = [
  {
    cityText: `Rostov-on-Don \n LCD admiral`,
    img: 'sliderimg1.jpg',
    areaText: '81 m2',
    repairText: '3.5 months'
  },
  {
    cityText: `Sochchi \t     \nThieves nThieves`,
    img: 'sliderimg2.jpg',
    areaText: '105 m2',
    repairText: '4 months'
  },
  {
    cityText: 'Rostov-on-Don \n Patriotic',
    img: 'sliderimg3.jpg',
    areaText: '93 m2',
    repairText: '3 months '
  }
] 

// поиск

const cityText = document.getElementById('city-text')
const img = document.getElementById('slider-photo')
const areaText = document.getElementById('area-text')
const repairText = document.getElementById('repair-text')


const setEntity = (index) => {
  cityText.innerText = entities[index].cityText
  img.src = `img/${entities[index].img}`
  areaText.innerText = entities[index].areaText
  repairText.innerText = entities[index].repairText
  
}


const prev = document.querySelector('.prev')
const next = document.querySelector('.next')

const pointSelector = document.querySelectorAll('.point-selector')
const citySelector = document.querySelectorAll('.city-selector')

let currentIndex = 0

// кнопки переключения слайдов

prev.addEventListener('click', () => {
  setEntity(currentIndex - 1);
  currentIndex -= 1;
  setFillOpacity(currentIndex);
  setChosenCity(currentIndex);
})
next.addEventListener('click', () => {
  setEntity(currentIndex + 1);
  currentIndex += 1;
  setFillOpacity(currentIndex);
  setChosenCity(currentIndex);
})

Полный код оставлю здесь - клик

Буду благодарен за помощь)

1
  • Всё сводится к управлению индексом... Вы его увеличиваете и уменьшаете. Тут вариант не один, можно индекс вычислять по формуле, а можно добавить проверку - если индекс больше entities.length то индекс = 0
    – InDevX
    17 апр 2021 в 13:26

1 ответ 1

0

Вот вариант с вычислением индекса по формуле:

const images = ['one', 'two', 'three', 'four', 'five', 'six', 'seven'];

const before = document.querySelector('.before');
const current = document.querySelector('.current');
const after = document.querySelector('.after');

const slide = () => {
  const index = (Number(current.dataset.index) + 1) % images.length;
  current.dataset.index = index;
  
  before.innerText = images[index - 1] || images[images.length - 1];
  current.innerText = images[index];
  after.innerText = images[index + 1] || images[0];

}

setInterval(slide, 2000);
<span class="before"></span>
<span class="current" data-index="-1"></span>
<span class="after"></span>

Также можно просто использовать условие index = ++index === images.length ? 0 : index

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.