Слайдер на чистом javascript
Стенограмма видео
Верстка:
<ul id="slider"> <li class="slide active"> <img src="img.jpg"> </li> <li class="slide"> <img src="img2.jpg"> </li> <li class="slide"> <img src="img.jpg"> </li> </ul>
<div class="arrows"> <span class="arrow next" id="next">Вправо</span> <span class="arrow prew" id="prew">Влево</span> </div>
Стили:
#slider {position: relative; overflow: hidden; width: 600px; height: 320px; margin: 20px auto; padding: 0; list-style: none;} .slide {position: absolute; width: 100%; height: 100%; transition: all 1s ease-in 0.1s; left:0;} .slide img {width: 100%;} .arrows {position: relative; margin: 0 auto; width: 600px;} .arrow {position: absolute; cursor: pointer;} .no_active {color: red;} .next {right: 0;}
Скрипт js:
var next = document.getElementById('next'); var prew = document.getElementById('prew'); var slides = document.getElementsByClassName('slide'); for(var i=0; i<slides.length; i++) { slides[i].style.zIndex = slides.length - i; }
next.onclick = function () { var activeEl = document.querySelector('.active'); if(activeEl.nextElementSibling) { activeEl.style.left = "-100%"; activeEl.classList.remove('active'); activeEl.nextElementSibling.classList.add('active'); this.classList.remove('no_active'); prew.classList.remove('no_active'); if(!activeEl.nextElementSibling.nextElementSibling) { this.classList.add('no_active'); } } }
prew.onclick = function () { var activeEl = document.querySelector('.active'); if(activeEl.previousElementSibling) { activeEl.previousElementSibling.style.left = "0%"; activeEl.classList.remove('active'); activeEl.previousElementSibling.classList.add('active'); this.classList.remove('no_active'); next.classList.remove('no_active'); if(!activeEl.previousElementSibling.previousElementSibling) { this.classList.add('no_active'); } } }