0

Пробую делать слайдер на JS по данному гайду.

window.addEventListener('load', function() {
  let line = document.getElementsByClassName('line')[0];
  let imgs = document.getElementsByClassName('line-item');
  let sliderWidth = document.getElementsByClassName('slider')[0].offsetWidth;
  let widthArr = [];
  let lineWidth = 0;

  let step = 0,
    offset = 0;
  // console.log(sliderWidth);

  for (let i = 0; i < imgs.length; i++) {
    widthArr.push(imgs[i].offsetWidth);
    // lineWidth += Math.ceil(imgs[i].offsetWidth);
    lineWidth += imgs[i].offsetWidth;
  }

  line.style.width = lineWidth + 'px';

  console.log(widthArr);

  function doSlide() {
    if (step === -1) {
      step = 0;
      line.style.left = '0px';
    } else {
      let diff = lineWidth - (offset + imgs[step].offsetWidth);
      if (diff > sliderWidth) {
        offset += imgs[step].offsetWidth;
        line.style.left = -offset + 'px';
        step++;
      } else {
        offset = lineWidth - sliderWidth;
        line.style.left = -offset + 'px';
        step = -1;
        offset = 0;
      }
    }
  }

  document.onclick = doSlide;
});
* {
  font-family: serif;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.slider {
  margin: 100px auto;
  width: 400px;
  /* height: 600px; */
  border: 1px solid red;
  /* overflow: hidden; */
  position: relative;
}

.line {
  height: 600px;
  position: relative;
  /* overflow: hidden; */
  left: 0;
  transition: all ease-in-out 0.7s;
}

.line-item {
  height: 100%;
  float: left;
}

.blok {
  width: 100px;
  background: red;
}

.blok-1 {
  width: 10px;
  background: green;
}
<main>
  <div class="slider">
    <div class="line">
      <img src="https://images.unsplash.com/photo-1559132837-f5007d4fb2fd?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=60" alt="" class="line-item">
      <img src="https://images.unsplash.com/photo-1559149740-88c6a43a4d09?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=60" alt="" class="line-item">
      <img src="https://images.unsplash.com/photo-1559163499-413811fb2344?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=60" alt="" class="line-item">
      <img src="https://images.unsplash.com/photo-1559200856-016e4562742d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=60" alt="" class="line-item">
      <img src="https://images.unsplash.com/photo-1559295628-07113de3334f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=60" alt="" class="line-item">
      <img src="https://images.unsplash.com/photo-1559234597-acca201b4a01?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=60" alt="" class="line-item">
      <div class="line-item blok"></div>
      <div class="line-item blok-1"></div>
    </div>
  </div>
</main>

При загрузке документа я с помощью offsetWidth рассчитываю ширину каждого элемента в блоке line, а потом задаю ширину для line как сумму всех offsetWidth. Все элементы внутри этого блока выравнены с помощью float:left; и они встают в линию друг за другом только тогда, когда ширина позволяет им это сделать.

Проблема в том, что, почему-то, ширина получается на 1 пиксель меньше нужной и последний элемент внутри line не помещается в линию и встает снизу. Это можно исправить, задав вручную ширину для line, равную очень много пикселей, например width: 9999999px или что-то в этом духе

Но вопрос в другом:

  1. Почему js подсчитывает ширину элементов так, что она получается чуток меньше, чем нужно?
  2. Почему у некоторых картинок Chrome отображает ширину как дробную, хотя она целая и как узнать значение ширины с дробной частью? image
2
  • Здесь можно записать lineWidth += (imgs[i].offsetWidth + 1); чтобы наверняка) 1 июн 2019 в 15:33
  • @OPTIMUSPRIME, это да. Можно даже просто изначально блоку line в стилях задать очень большое значение width и не парится с этим в js, но вопрос в том, почему js неправильно посчитал ширину и откуда у картинок взялось дробное значение в ширине?
    – Drovosek
    1 июн 2019 в 17:32

1 ответ 1

1

Дело в том, что ширина изображений, возвращаемая свойством offsetWidth действительно недостаточно точная. Для точных вычислений можно воспользоваться getBoundingClientRect().

откуда у картинок взялось дробное значение в ширине

Возьмем для примера первую картинку https://images.unsplash.com/photo-1559132837-f5007d4fb2fd?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=60.

У нее оригинальные размеры 700х467. Вы задаете высоту всем картинкам 600 пикселей, следовательно ширина картинки станет 700*(600/467) = 899.3576017130621

Пример:

window.addEventListener('load', function() {
  let line = document.getElementsByClassName('line')[0];
  let imgs = document.getElementsByClassName('line-item');
  let sliderWidth = document.getElementsByClassName('slider')[0].offsetWidth;
  let widthArr = [];
  let lineWidth = 0;

  let step = 0,
    offset = 0;
  // console.log(sliderWidth);

  for (let i = 0; i < imgs.length; i++) {
    widthArr.push(imgs[i].offsetWidth);
    console.log(imgs[i].offsetWidth, imgs[i].getBoundingClientRect().width);
    lineWidth += imgs[i].getBoundingClientRect().width;
  }
  console.log(lineWidth);
  line.style.width = lineWidth + 'px';



  function doSlide() {
    if (step === -1) {
      step = 0;
      line.style.left = '0px';
    } else {
      let diff = lineWidth - (offset + imgs[step].offsetWidth);
      if (diff > sliderWidth) {
        offset += imgs[step].offsetWidth;
        line.style.left = -offset + 'px';
        step++;
      } else {
        offset = lineWidth - sliderWidth;
        line.style.left = -offset + 'px';
        step = -1;
        offset = 0;
      }
    }
  }

  document.onclick = doSlide;
});
* {
  font-family: serif;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.slider {
  margin: 100px auto;
  width: 400px;
  /* height: 600px; */
  border: 1px solid red;
  /* overflow: hidden; */
  position: relative;
}

.line {
  height: 600px;
  position: relative;
  /* overflow: hidden; */
  left: 0;
  transition: all ease-in-out 0.7s;
}

.line-item {
  height: 100%;
  float: left;
}

.blok {
  width: 100px;
  background: red;
}

.blok-1 {
  width: 10px;
  background: green;
}
<main>
  <div class="slider">
    <div class="line">
      <img src="https://images.unsplash.com/photo-1559132837-f5007d4fb2fd?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=60" alt="" class="line-item">
      <img src="https://images.unsplash.com/photo-1559149740-88c6a43a4d09?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=60" alt="" class="line-item">
      <img src="https://images.unsplash.com/photo-1559163499-413811fb2344?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=60" alt="" class="line-item">
      <img src="https://images.unsplash.com/photo-1559200856-016e4562742d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=60" alt="" class="line-item">
      <img src="https://images.unsplash.com/photo-1559295628-07113de3334f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=60" alt="" class="line-item">
      <img src="https://images.unsplash.com/photo-1559234597-acca201b4a01?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=60" alt="" class="line-item">
      <div class="line-item blok"></div>
      <div class="line-item blok-1"></div>
    </div>
  </div>
</main>

Ваш ответ

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

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