Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Простой слайдер. (https://javascript.ru/forum/misc/80713-prostojj-slajjder.html)

Сергей Ракипов 19.07.2020 14:57

Простой слайдер.
 
Нужно что бы кликая по стрелку сдвигалось на одну картинку, достигнув конца прекратило сдвигается. То есть не бесконечная карусель.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.foto {
    position: relative;
    top: 0px;
    width: 640px;
    margin: 100px auto 0px;
}
.foto_blok{
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    overflow-x: hidden;
}
.foto_blok img{

}
.strelka_1{
    width: 40px;
    height: 320px;
    position: absolute;
    top: 0px;
    left: 0px;
    cursor: pointer;
    background-image: url(https://www.rakipov.ru/files/strelka.svg);
    background-repeat: no-repeat;
    background-position: top left;
    opacity: .8;
    z-index: 10;
}
.strelka_2{
    width: 40px;
    height: 320px;
    position: absolute;
    top: 0px;
    right: 0px;
    cursor: pointer;
    background-image: url(https://www.rakipov.ru/files/strelka.svg);
    background-repeat: no-repeat;
    background-position: top right;
    opacity: .8;
    transform: rotate(180deg);
    z-index: 10;
}
</style>
</head>
<body>
<div class="foto">
    <div class="strelka_1"></div>
    <div class="foto_blok">
        <img src="https://www.rakipov.ru/files/1.jpg" height="320" width="320" alt="">
        <img src="https://www.rakipov.ru/files/2.jpg" height="320" width="320" alt="">
        <img src="https://www.rakipov.ru/files/3.jpg" height="320" width="320" alt="">
        <img src="https://www.rakipov.ru/files/4.jpg" height="320" width="320" alt="">
        <img src="https://www.rakipov.ru/files/5.jpg" height="320" width="320" alt="">
        <img src="https://www.rakipov.ru/files/6.jpg" height="320" width="320" alt="">
        <img src="https://www.rakipov.ru/files/7.jpg" height="320" width="320" alt="">
        <img src="https://www.rakipov.ru/files/9.jpg" height="320" width="320" alt="">
    </div>
    <div class="strelka_2"></div>
</div>
<script>
const strelka_1 = document.querySelector(".strelka_1");
const strelka_2 = document.querySelector(".strelka_2");
const foto_blok = document.querySelector(".foto_blok");


let slader_2 = () => {

    console.log(`клик2`);
}
strelka_2.addEventListener("click", slader_2);

let slader_1 = () => {

    console.log(`клик1`);
}
strelka_1.addEventListener("click", slader_1);
</script>
</body>
</html>


Не могу понять что и как смещать, влево и вправо, пробую и отступом, и позицией, и трансформом, и все как то коряво.

рони 19.07.2020 16:05

слайдер с ограничением прокрутки
 
Сергей Ракипов,

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.foto {
    position: relative;
    top: 0px;
    width: 640px;
    margin: 100px auto 0px;
    overflow-x: hidden;
}
.foto_blok{
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    transition: 1s;

}
.foto_blok img{
   flex: 0 1 0;
}
.strelka_1{
    width: 40px;
    height: 320px;
    position: absolute;
    top: 0px;
    left: 0px;
    cursor: pointer;
    background-image: url(https://www.rakipov.ru/files/strelka.svg);
    background-repeat: no-repeat;
    background-position: top left;
    opacity: .8;
    z-index: 10;
}
.strelka_2{
    width: 40px;
    height: 320px;
    position: absolute;
    top: 0px;
    right: 0px;
    cursor: pointer;
    background-image: url(https://www.rakipov.ru/files/strelka.svg);
    background-repeat: no-repeat;
    background-position: top right;
    opacity: .8;
    transform: rotate(180deg);
    z-index: 10;
}

.hide {
    visibility: collapse;
}

</style>
</head>
<body>
<div class="foto">
    <div class="strelka_1"></div>
    <div class="foto_blok">
        <img src="https://www.rakipov.ru/files/1.jpg" height="320" width="320" alt="">
        <img src="https://www.rakipov.ru/files/2.jpg" height="320" width="320" alt="">
        <img src="https://www.rakipov.ru/files/3.jpg" height="320" width="320" alt="">
        <img src="https://www.rakipov.ru/files/4.jpg" height="320" width="320" alt="">
        <img src="https://www.rakipov.ru/files/5.jpg" height="320" width="320" alt="">
        <img src="https://www.rakipov.ru/files/6.jpg" height="320" width="320" alt="">
        <img src="https://www.rakipov.ru/files/7.jpg" height="320" width="320" alt="">
        <img src="https://www.rakipov.ru/files/9.jpg" height="320" width="320" alt="">
    </div>
    <div class="strelka_2"></div>
</div>
<script>
const strelka_1 = document.querySelector(".strelka_1");
const strelka_2 = document.querySelector(".strelka_2");
const foto_blok = document.querySelector(".foto_blok");
const len = foto_blok.children.length - 1;
let index = 0;
const upIndex = up => index = Math.max(0, Math.min(len, index + up));
const move = _ => {
let x = index * 320, max = foto_blok.scrollWidth - foto_blok.clientWidth;
strelka_1.classList.toggle("hide", x && x >= max);
strelka_2.classList.toggle("hide", !index);
if(x > max) {index--; };
x = Math.min(x, max);
foto_blok.style.transform = `translateX(${-x}px)`;
}
let slader_2 = () => {
    upIndex(-1) ;
    move();
}
strelka_2.addEventListener("click", slader_2);

let slader_1 = () => {
    upIndex(1);
    move();
}
strelka_1.addEventListener("click", slader_1);
window.addEventListener("load", move);
</script>
</body>
</html>

Сергей Ракипов 20.07.2020 04:24

рони,
Спасибо.

У меня вопрос

а зачем такие значение?

.foto_blok img{
flex: 0 1 0;
}


как понять эту функцию ?

const upIndex = up => index = Math.max(0, Math.min(len, index + up));


что за подчеркивание в параметрах ?

const move = _ =>

Сергей Ракипов 20.07.2020 04:42

Увидел новый класс hide

И попробовал сам сделать, но так как я не понимаю как поставить условия, не выходит.

.hide{
opacity: 0;
}


let slader_1 = () => {
upIndex(1);
move();
strelka_2.classList.remove("hide");
}
strelka_1.addEventListener("click", slader_1);


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

рони 20.07.2020 07:11

Цитата:

Сообщение от Сергей Ракипов
а зачем такие значение?

.foto_blok img{
flex: 0 1 0;
}

чтоб картинка не растягивалась и не сжималась.
Цитата:

Сообщение от Сергей Ракипов
как понять эту функцию ?

const upIndex = up => index = Math.max(0, Math.min(len, index + up));

чтобы не прибавили к индексу, индекс останется в пределах от ноля до len(количество всех картинок минус 1).
Цитата:

Сообщение от Сергей Ракипов
что за подчеркивание в параметрах ?

const move = _ =>

неиспользуемый параметр, тоже самое что move = () =>

Сергей Ракипов 20.07.2020 07:23

рони,
Спасибо, так чуть более яснее

рони 20.07.2020 08:06

Цитата:

Сообщение от Сергей Ракипов
класс hide

добавил, смотрите пост #2 снова, строки 83 и 84.

Сергей Ракипов 20.07.2020 08:18

рони,
Спасибо !

рони 20.07.2020 09:14

Сергей Ракипов,
подумайте какой параметр можно использовать, вместо вычисления index * 320? это поможет использовать картинки любой ширины.

Сергей Ракипов 20.07.2020 11:26

рони,
offsetWidth ?!

рони 20.07.2020 11:42

Сергей Ракипов,
положение картинки относительно родителя?

Сергей Ракипов 20.07.2020 11:45

рони,
Нет, я просто как думаю.
Надо прочитать сколько пихалей следующая картинка и при клике сдвинуть ее на это количество.

рони 20.07.2020 11:50

простейший слайдер кнопки управления
 
Сергей Ракипов,
:-?
в примере ниже, картинки разной ширины.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.foto {
    position: relative;
    top: 0px;
    width: 640px;
    margin: 100px auto 0px;
    overflow-x: hidden;
}
.foto_blok{
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    transition: 1s;

}
.foto_blok img{
   flex: 0 1 0;
}
.strelka_1{
    width: 40px;
    height: 320px;
    position: absolute;
    top: 0px;
    left: 0px;
    cursor: pointer;
    background-image: url(https://www.rakipov.ru/files/strelka.svg);
    background-repeat: no-repeat;
    background-position: top left;
    opacity: 0;
    z-index: 10;

}
.strelka_2{
    width: 40px;
    height: 320px;
    position: absolute;
    top: 0px;
    right: 0px;
    cursor: pointer;
    background-image: url(https://www.rakipov.ru/files/strelka.svg);
    background-repeat: no-repeat;
    background-position: top right;
    opacity: 0;
    transform: rotate(180deg);
    z-index: 10;
}

.hide {
    visibility: collapse;
}

.foto:hover .strelka_1, .foto:hover .strelka_2{
    opacity: .8;
    transition: 1.2s;
}

</style>
</head>
<body>
<div class="foto">
    <div class="strelka_1"></div>
    <div class="foto_blok">
        <img src="https://www.rakipov.ru/files/1.jpg" height="320" width="370" alt="">
        <img src="https://www.rakipov.ru/files/2.jpg" height="320" width="320" alt="">
        <img src="https://www.rakipov.ru/files/3.jpg" height="320" width="320" alt="">
        <img src="https://www.rakipov.ru/files/4.jpg" height="320" width="520" alt="">
        <img src="https://www.rakipov.ru/files/5.jpg" height="320" width="320" alt="">
        <img src="https://www.rakipov.ru/files/6.jpg" height="320" width="320" alt="">
        <img src="https://www.rakipov.ru/files/7.jpg" height="320" width="320" alt="">
        <img src="https://www.rakipov.ru/files/9.jpg" height="320" width="420" alt="">
    </div>
    <div class="strelka_2"></div>
</div>
<script>
const strelka_1 = document.querySelector(".strelka_1");
const strelka_2 = document.querySelector(".strelka_2");
const foto_blok = document.querySelector(".foto_blok");
const children  = foto_blok.children;
const len = children.length - 1;
let index = 0;
const upIndex = up => index = Math.max(0, Math.min(len, index + up));
const move = _ => {
let x = children[index].offsetLeft, max = foto_blok.scrollWidth - foto_blok.clientWidth;
strelka_1.classList.toggle("hide", x && x > max);
strelka_2.classList.toggle("hide", !index);
if(x > max) {index--; };
x = Math.min(x, max);
foto_blok.style.transform = `translateX(${-x}px)`;
}
let slader_2 = () => {
    upIndex(-1) ;
    move();
}
strelka_2.addEventListener("click", slader_2);

let slader_1 = () => {
    upIndex(1);
    move();
}
strelka_1.addEventListener("click", slader_1);
window.addEventListener("load", move);
</script>
</body>
</html>

рони 20.07.2020 11:54

Цитата:

Сообщение от Сергей Ракипов
Надо прочитать сколько пихалей следующая картинка и при клике сдвинуть ее на это количество.

а если захочется сдвинуть не на соседнюю картинку, а на вторую или через 10? код выше позволяет это сделать/добавить (точечная навигация).

Сергей Ракипов 20.07.2020 11:55

рони,
Надо все это переварить и осознать


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