Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Автоматическая смена активного класса по таймеру (https://javascript.ru/forum/misc/77216-avtomaticheskaya-smena-aktivnogo-klassa-po-tajjmeru.html)

MiHALbI4 07.04.2019 11:47

Автоматическая смена активного класса по таймеру
 
Всем привет!

Есть, например, 6 блоков. Изначально активный css-класс у первого (для универсальности можно учесть любую изначальную позицию активного класса). Нужно через секунду переключить активный класс на второй, потом через секунду на третий и т.д. Как дойдет до последнего - начать сначала и так бесконечно. Но! Есть еще несколько условий:

1) При наведении мышкой на родительский блок смена класса останавливается и возобновляется когда мы убираем мышь. Возобновляется через время, равное скорости переключения активного класса.

2) Так же, во время автоматической смены классов по таймеру мы можем нажать на любой из этих блоков, тогда он станет с активным классом и автоматическое переключение продолжится с него по таймеру.

Можно написать на чистом JS или на JQuery. Для удобства ссылка на jsfiddle: https://jsfiddle.net/3nLx5k24/

Заранее спасибо!

рони 07.04.2019 12:32

Цитата:

Сообщение от MiHALbI4
на JQuery

https://javascript.ru/forum/showthread.php?p=398953

Malleys 07.04.2019 15:34

Цитата:

Сообщение от MiHALbI4
Можно написать на чистом JS

Не получится, так и так придётся использовать DOM API... https://jsfiddle.net/q7oram3c/

рони 07.04.2019 16:59

бесконечная карусель с паузой
 
Цитата:

Сообщение от MiHALbI4
для универсальности можно учесть любую изначальную позицию активного класса

Malleys, :thanks:

<!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>

рони 08.04.2019 18:21

:write:
строка 60 смена направления setActiveElement(addIndex = -1)


Часовой пояс GMT +3, время: 08:53.