<div class="wrap"> <div class="b-carousel js-carousel"> <button class="b-carousel__prev js-carousel__prev">Prev</button> <button class="b-carousel__next js-carousel__next">Next</button> <div class="b-carousel__wrap js-carousel__wrap"> <div class="b-carousel__item"> <img src="..." alt="" class="b-carousel__img"> </div> <div class="b-carousel__item"> <img src="..." alt="" class="b-carousel__img"> </div> <div class="b-carousel__item"> <img src="..." alt="" class="b-carousel__img"> </div> <div class="b-carousel__item"> <img src="..." alt="" class="b-carousel__img"> </div> </div> </div> </div>
.b-carousel { width: 100%; overflow: hidden; position: relative; box-sizing: border-box; border: 1px solid; } .b-carousel__prev, .b-carousel__next { position: absolute; top: 50%; left: 20px; width: 50px; height: 50px; background: #fff; transform: translateY(-50%) translateZ(0); cursor: pointer; text-indent: 100%; white-space: nowrap; overflow: hidden; z-index: 3; } .b-carousel__next { left: auto; right: 20px; } .b-carousel__wrap { display: flex; transition: transform .5s; will-change: transform; position: relative; z-index: 1; height: 100%; } .b-carousel__item { flex: 0 0 100%; overflow: hidden; display: flex; align-items: center; justify-content: center; } .b-carousel__img { width: 100%; display: block; }
function Carousel(setting) { /* Scope privates methods and properties */ let privates = {}; /* Privates properties */ privates.setting = setting; privates.sel = { "main": document.querySelector(privates.setting.main), "wrap": document.querySelector(privates.setting.wrap), "children": document.querySelector(privates.setting.wrap).children, "prev": document.querySelector(privates.setting.prev), "next": document.querySelector(privates.setting.next) }; privates.opt = { "position": 0, "max_position": document.querySelector(privates.setting.wrap).children.length }; // Control if(privates.sel.prev !== null) { privates.sel.prev.addEventListener('click', () => { this.prev_slide(); }); } if(privates.sel.next !== null) { privates.sel.next.addEventListener('click', () => { this.next_slide(); }); } }
/* Public methods */ // Prev slide this.prev_slide = () => { --privates.opt.position; if(privates.opt.position < 0) { privates.sel.wrap.classList.add('s-notransition'); privates.opt.position = privates.opt.max_position - 1; } privates.sel.wrap.style["transform"] = `translateX(-${privates.opt.position}00%)`; }; // Next slide this.next_slide = () => { ++privates.opt.position; if(privates.opt.position >= privates.opt.max_position) { privates.opt.position = 0; } privates.sel.wrap.style["transform"] = `translateX(-${privates.opt.position}00%)`; };
new Carousel({ "main": ".js-carousel", "wrap": ".js-carousel__wrap", "prev": ".js-carousel__prev", "next": ".js-carousel__next" });
Source: https://habr.com/ru/post/327246/
All Articles