Javascript-форум (https://javascript.ru/forum/)
-   jQuery (https://javascript.ru/forum/jquery/)
-   -   Как заставить раздельно работать слайдеры с одинаковыми классами? (https://javascript.ru/forum/jquery/77641-kak-zastavit-razdelno-rabotat-slajjdery-s-odinakovymi-klassami.html)

рони 31.05.2019 19:44

Malleys,
:thanks:

DenKuzmin17 31.05.2019 19:55

Цитата:

Сообщение от Malleys (Сообщение 508598)
А вам принципиально важно использовать ту библиотеку или можно заменить

Не принципиально. Просто начал уже на этом делать. Мне чем проще тем лучше, желательно вообще без плагинов. Попробую потом то, что Вы предлагает выше.

PS transition в процентах с текущим плагином можно реализовать?

Malleys 31.05.2019 20:32

Цитата:

Сообщение от DenKuzmin17
PS transition в процентах с текущим плагином можно реализовать?

Да, можно! https://codepen.io/Malleys/pen/byQjOM?editors=0010

рони 31.05.2019 21:06

:-?
зачем это
var value = (distance < 0 ? "" : "-") + Math.abs(distance).toString();

вариант без этой строки
scrollImages(distance, duration) {
        this.slider.css("transition-duration", (duration / 1000).toFixed(1) + "s");
        this.slider.css("transform", "translate(" + (100 * -distance / this.maxImages) + "%,0)");
    }

DenKuzmin17 31.05.2019 23:45

this.currentImg + 0.0025 * distance,
          duration
"0.0025" это что?

рони 01.06.2019 00:12

:write: вариант ...
if (direction == "left") {
                this.scrollImages(
                    this.currentImg + distance / this.IMG_WIDTH ,
                    duration
                );
            } else if (direction == "right") {
                this.scrollImages(
                    this.currentImg - distance / this.IMG_WIDTH ,
                    duration
                );
            }

рони 01.06.2019 00:32

:write: всё в сборе ...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CodePen - Malleys JQuery Touch Slider</title>
<style>
            * {
    margin: 0;
    padding: 0;
}
section {
    width: 100%;
    height: 100vh;
    background: #ececec;
}
.block {
    width: 500px;
    height: 100px;
    margin: 10px auto;
}
.slider-box {
    display: flex;
    overflow: hidden;
    border: 1px solid #909090;
}
.slider {
    display: flex;
    transition: 0.5s;
}
.slide {
    display: flex;
    width: 500px;
    height: 100px;
    align-items: center;
    justify-content: center;
}

/* :focus:hover {
    outline: none;
} */
        </style>

</head>
<body translate="no">
<section>
<div class="block 1">
<div class="slider-box">
<div class="slider">
<div class="slide">1 / 3</div>
<div class="slide">2 / 3</div>
<div class="slide">3 / 3</div>
</div>
</div>
</div>
<hr>
<div class="block 2">
<div class="slider-box">
<div class="slider">
<div class="slide">1 / 4</div>
<div class="slide">2 / 4</div>
<div class="slide">3 / 4</div>
<div class="slide">4 / 4</div>
</div>
</div>
</div>
<hr>
<div class="block 3">
<div class="slider-box">
<div class="slider">
<div class="slide">1 / 2</div>
<div class="slide">2 / 2</div>
</div>
</div>
</div>
<hr>
</section>
<script src='https://profforma.store/assets/js/jquery.min.js'></script>
<script src='https://profforma.store/assets/js/jquery.touchSwipe.min.js'></script>
<script>



class Slider {
    constructor(slider) {
        this.IMG_WIDTH = 500;
        this.currentImg = 0;
        this.speed = 500;

        this.swipeStatus = this.swipeStatus.bind(this);
        this.keyboardHandler = this.keyboardHandler.bind(this);

        this.slider = $(slider);
        this.slider
            .parent()
            .attr("tabIndex", 0)
            .on("blur focus click", this.keyboardHandler)
            .swipe({
                triggerOnTouchEnd: true,
                triggerOnTouchLeave: true,
                swipeStatus: this.swipeStatus,
                allowPageScroll: "vertical",
                threshold: 75
            });
        this.maxImages = this.slider.find(">*").length;
    }

    keyboardHandler(event) {
        if (event.type === "focus") {
            document.addEventListener("keydown", this.keyboardHandler);
            this.constructor.activeInstance = this;
        } else if (event.type === "blur") {
            document.removeEventListener("keydown", this.keyboardHandler);
            this.constructor.activeInstance = null;
        } else if (event.type === "keydown") {
            if (event.keyCode === 37) this.previousImage();
            if (event.keyCode === 39) this.nextImage();
        } else {
            this.slider.parent().focus();
        }

        return true;
    }

    swipeStatus(event, phase, direction, distance) {
        //If we are moving before swipe, and we are going L or R in X mode, or U or D in Y mode then drag.
        if (phase == "move" && (direction == "left" || direction == "right")) {
            var duration = 0;

            if (direction == "left") {
                this.scrollImages(
                    this.currentImg + distance / this.IMG_WIDTH ,
                    duration
                );
            } else if (direction == "right") {
                this.scrollImages(
                    this.currentImg - distance / this.IMG_WIDTH ,
                    duration
                );
            }
        } else if (phase == "cancel") {
            this.scrollImages(this.currentImg, this.speed);
        } else if (phase == "end") {
            if (direction == "right") {
                this.previousImage();
            } else if (direction == "left") {
                this.nextImage();
            }
        }
    }

    scrollImages(distance, duration) {
        this.slider.css({"transition-duration" : (duration / 1000).toFixed(1) + "s",
                         "transform" : "translate(" + (100 * -distance / this.maxImages) + "%,0)"});
    }

    previousImage() {
        this.currentImg = Math.max(this.currentImg - 1, 0);
        this.scrollImages(this.currentImg, this.speed);
    }

    nextImage() {
        this.currentImg = Math.min(this.currentImg + 1, this.maxImages - 1);
        this.scrollImages(this.currentImg, this.speed);
    }
}

$(() => {
    for (const element of $(".slider")) {
        new Slider(element);
    }
});

    </script>
</body>
</html>

Malleys 01.06.2019 15:07

Цитата:

Сообщение от DenKuzmin17
"0.0025" это что?

Коэффициент, пропорционально которому сдвигается слайд.

Вот, написал собственную реализацию слайдера без той сторонней библиотеки. https://codepen.io/Malleys/pen/byQjOM?editors=0010 Теперь можно начать перетаскивать слайд и курсор мыши вывести за рамки окна браузера и оно правильно обрабатывается! Что-то не нашёл ни одной библиотеки, которые бы это учитывали.

рони 01.06.2019 15:47

Malleys,
зачем эта строка?
this.slider[Symbol.for("slider")] = this;

или как это работает?
pointer.addEventListener("start", ({ target }) => {
    Slider.activeElement = (
    target.matches(".slider") && target ||
    target.closest(".slider") ||
    {})[
    Symbol.for("slider")];
});

не понимаю что тут происходит, зачем нужно использовать Symbol.for("slider")?

Malleys 01.06.2019 16:02

Цитата:

*Malleys*,
зачем эта строка?
<pre class="source brush:js;light:true">
this.slider[Symbol.for("slider")] = this;
</pre>
Чтобы можно было обратиться к представителю класса Slider через элемент, к которому он привязан. Поскольку я определил только одного представителя SinglePointer, и на нём прослушиваются события start, move, end... то через него можно узнать, на каком элементе типа HTMLElement началось перетаскивание... а свойство Symbol.for("slider") помогает получить ссылку на такой слайдер (объект типа Slider), который был инициализирован тем самым элементом, над которым началось перетаскивание.

Цитата:

Сообщение от рони
не понимаю что тут происходит, зачем нужно использовать Symbol.for("slider")?

Сначала находится ближайший элемент с селектором .slider, а затем берётся ссылка на представителя класса Slider, которым этот элемент был инициализирован!


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