Сообщение от MiHALbI4
|
для универсальности можно учесть любую изначальную позицию активного класса
|
Malleys,
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
<style>
.item {
display: inline-block;
margin: 10px;
width: 100px;
height: 100px;
background-color: blue;
}
.active {
background-color: red;
}
</style>
<script>
addEventListener("load",function(){
class PolySwitch {
constructor(root, delay=1000, index=0) {
this.root = root;
this.delay = delay;
this.index = index;
this.children = [...root.children];
this.setActiveElement(0);
this.eventHandler = this.eventHandler.bind(this);
this.timeout = setTimeout(this.loop.bind(this), this.delay);
this.root.addEventListener("pointerover", this.eventHandler);
this.root.addEventListener("pointerout", this.eventHandler);
this.root.addEventListener("click", this.eventHandler);
}
loop() {
this.setActiveElement();
this.timeout = setTimeout(this.loop.bind(this), this.delay);
}
eventHandler(event) {
if(event.type === "pointerover") {
clearTimeout(this.timeout);
}
if(event.type === "pointerout") {
this.timeout = setTimeout(this.loop.bind(this), this.delay);
}
if(event.type === "click") {
const target = event.target.closest(".item");
if(target) {
const addIndex = this.children.indexOf(target) - this.index;
this.setActiveElement(addIndex);
}
}
}
setActiveElement(addIndex = 1) {
this.children[this.index].classList.remove("active");
this.index = (this.index + addIndex + this.children.length) % this.children.length;
this.children[this.index].classList.add("active");
}
}
new PolySwitch(document.querySelector(".list"), 1000, 2);
// new PolySwitch(document.querySelector(".list"));
})
</script>
</head>
<body>
<div class="list">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</body>
</html>