Javascript-форум (https://javascript.ru/forum/)
-   Events/DOM/Window (https://javascript.ru/forum/events/)
-   -   Некорректная работа слайдшоу (https://javascript.ru/forum/events/75320-nekorrektnaya-rabota-slajjdshou.html)

oleg901 20.09.2018 18:15

Некорректная работа слайдшоу
 
Доброго времени суток) Решил попрактиковаться с js нашел интересный слайдер решил повторить. Вроде как все вышло, но при первом переходе между классами происходит резко дальше заменяется все как надо. Думал что проблема в последовательности команд пробовал всякие вариации менял местами и ничего. Объясните в чем проблема и как ее решить за ранее благодарен)
<!DOCTYPE html>
<html lang="ru">
    <head>
        <meta charset="utf-8" />
        <title>Документ без названия</title>
        <style>



/* sleider3---------------------------------- */

#slide3{
width:400px;
height:400px;
margin:auto;


}


#img1{
	margin:auto;
	background-color:#7E6497;
	width:400px;
	height:400px;
	position:absolute;
	
}

#img2{
	margin:auto;
	background-color:#D0FF00;
	width:400px;
	height:400px;
	position:absolute;
	
}

#img3{
	margin:auto;
	background-color:#00C8FF;
	width:400px;
	height:400px;
	position:absolute;


}


#img4{
	margin:auto;
	background-color:red;
	width:400px;
	height:400px;
	position:absolute;
	
	
}


.of{
	display: none;
}
.active{
	display: block !important;
	
}




  </style>
       
    </head>
    <body>
 		
 		<div id='an3'><header id="slide3">
 			<div id=slider>
 				<div id="img1" class="of active"></div>
				<div id="img2" class="of"></div>
				<div id="img3" class="of"></div>
				<div id="img4" class="of"></div>
 			</div>

 			<div id="levo1"></div>
 			<div id="pravo1"></div>
 		</header></div>
		
		</fieldset>
 <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.js"></script>
     <script>
     	
 	$(function(){

	
	var timer = setTimeout(function test(){
	var active = $('.active');
	var ImgIndex = $('.active').index();
	var NextImgIndex =  ImgIndex + 1;
	var NextImg = $(' #slider > .of').eq(NextImgIndex);
	active.fadeOut(1500);
	active.removeClass('active');
	if( NextImgIndex === ($('#slider > .of:last').index()+1)){
			$(' #slider > .of').eq(0).fadeIn(1500);
			$(' #slider > .of').eq(0).addClass('active');  
	}
		else{
	NextImg.fadeIn(1500);
	NextImg.addClass('active');
}

				setTimeout(test, 5000);
		
		},5000)


 
 })
     </script>
    </body>
</html>

рони 20.09.2018 18:51

oleg901,
в jQuery setTimeout для таких слайдеров не нужен

oleg901 20.09.2018 19:12

Объясните пожалуйста как решить эту маленькую ошибку. До этого скрипт обрабатывался кликом и проблема была такая же. Все равно первый раз смена цветов резче чем во все остальные. Если не использовать setTimeout тогда какая альтернатива?

рони 20.09.2018 19:46

бесконечная карусель jQuery
 
oleg901,
<!DOCTYPE html>
<html lang="ru">
    <head>
        <meta charset="utf-8" />
        <title>Документ без названия</title>
        <style>



/* sleider3---------------------------------- */

#slide3{
width:400px;
height:400px;
margin:auto;


}


#img1{
    margin:auto;
    background-color:#7E6497;
    width:400px;
    height:400px;
    position:absolute;

}

#img2{
    margin:auto;
    background-color:#D0FF00;
    width:400px;
    height:400px;
    position:absolute;

}

#img3{
    margin:auto;
    background-color:#00C8FF;
    width:400px;
    height:400px;
    position:absolute;


}


#img4{
    margin:auto;
    background-color:red;
    width:400px;
    height:400px;
    position:absolute;
}



.of{
    font-size: 70px;
    line-height: 400px;
    text-align: center;
    display:  none;
}


  </style>

    </head>
    <body>

 		<div id='an3'><header id="slide3">
 			<div id=slider>
 				<div id="img1" class="of">1</div>
                <div id="img2" class="of">2</div>
                <div id="img3" class="of">3</div>
                <div id="img4" class="of">4</div>
 			</div>

 			<div id="levo1"></div>
 			<div id="pravo1"></div>
 		</header></div>


 <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.js"></script>
     <script>
$(function() {
    var Img = $(".of"),
        ImgLength = Img.length,
        ImgIndex = 0,
        pause = 5000,
        duration = 1500;
    Img.eq(ImgIndex).fadeIn(duration, show);

    function show() {
        Img.delay(pause).eq(ImgIndex).fadeOut(duration, show);
        ImgIndex++;
        ImgIndex %= ImgLength;
        Img.eq(ImgIndex).fadeIn(duration)
    }
});
     </script>
    </body>
</html>

рони 20.09.2018 20:50

бесконечная карусель js
 
oleg901,
<!DOCTYPE html>
<html lang="ru">
    <head>
        <meta charset="utf-8" />
        <title>Документ без названия</title>
        <style>



/* sleider3---------------------------------- */

#slide3{
width:400px;
height:400px;
margin:auto;
 position: relative;

}


#img1{
    margin:auto;
    background-color:#7E6497;
    width:400px;
    height:400px;
    position:absolute;

}

#img2{
    margin:auto;
    background-color:#D0FF00;
    width:400px;
    height:400px;
    position:absolute;

}

#img3{
    margin:auto;
    background-color:#00C8FF;
    width:400px;
    height:400px;
    position:absolute;


}


#img4{
    margin:auto;
    background-color:red;
    width:400px;
    height:400px;
    position:absolute;
}



.of{
    font-size: 70px;
    line-height: 400px;
    text-align: center;
     opacity: 0;
     z-index: 0;
     transform: scale(0);
     transition: 1.5s;
}
.active{
    transition: 1s;
    opacity: 1;
    z-index: 100;
    transform: scale(1);
}

  </style>

    </head>
    <body>

 		<div id='an3'><header id="slide3">
 			<div id=slider>
 				<div id="img1" class="of">1</div>
                <div id="img2" class="of">2</div>
                <div id="img3" class="of">3</div>
                <div id="img4" class="of">4</div>
 			</div>

 			<div id="levo1"></div>
 			<div id="pravo1"></div>
 		</header></div>



     <script>
 document.addEventListener('DOMContentLoaded', function() {
      var Img = document.querySelectorAll(".of"),
        ImgLength = Img.length,
        ImgIndex = ImgLength - 1,
        pause = 5000;
        function show() {
        Img[ImgIndex].classList.remove("active");
        ImgIndex++;
        ImgIndex %= ImgLength;
        Img[ImgIndex].classList.add("active");
        window.setTimeout(show, pause);
        };
        show()
  });
    </script>
    </body>
</html>

oleg901 21.09.2018 11:51

Спасибо, я понял свою ошибку. Посоветуете какой-нибудь задачник по JavaScript. Книгу я уже нашел на форуме. А вот что касается практики может знаете что-то подобное?

рони 21.09.2018 12:02

Цитата:

Сообщение от oleg901
Посоветуете какой-нибудь задачник

на форуме ежедневно новые задачи.
http://code.mu/tasks/javascript/base...novichkov.html
практика - сделайте сайт от и до самостоятельно.

oleg901 21.09.2018 12:34

Спасибо

oleg901 21.09.2018 20:17

Рони, еще один вопрос захотел сделать так что бы слайдер реагировал не только на событие клик, а и на таймер. Ну что бы цвета менялись на автомате. И получилось у меня это криво. Как реализовать данную задачу?

oleg901 21.09.2018 20:26

Тема закрыта нашел ответ


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