Тема: custom slider
Показать сообщение отдельно
  #3 (permalink)  
Старый 27.02.2016, 11:46
Профессор
Отправить личное сообщение для s24344 Посмотреть профиль Найти все сообщения от s24344
 
Регистрация: 12.08.2015
Сообщений: 206

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>slider</title>
	<link rel="stylesheet" href="css/normalize.css">
	<link rel="stylesheet" href="css/styles.css">
</head>
<body>
	<div class="container">

		<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugiat laboriosam esse rem ut velit dolores accusamus voluptatem possimus, temporibus, earum enim autem, impedit pariatur necessitatibus. Possimus placeat ad eos velit.</p>

		<!-- slider -->

		<div class="slider">

			<div class="slider__list--wrap">

				<ul class="slider__list">
					<li class="slider__item active">
						<img src="images/1.jpg" alt="">
					</li>
					<li class="slider__item">
						<img src="images/2.jpg" alt="">
					</li>
					<li class="slider__item">
						<img src="images/3.jpg" alt="">
					</li>
					<li class="slider__item"> 
						<img src="images/4.jpg" alt="">
					</li>
				</ul>

				<!-- <ul class="slider__dots">
					<li class="slider__dots-item">
						<a class="slider__dots-link" href="#"></a>
					</li>
					<li class="slider__dots-item">
						<a class="slider__dots-link" href="#"></a>
					</li>
					<li class="slider__dots-item">
						<a class="slider__dots-link" href="#"></a>
					</li>
					<li class="slider__dots-item">
						<a class="slider__dots-link" href="#"></a>
					</li>
				</ul> -->

			</div>
			
		</div>

		<ul class="slider__dots clearfix"></ul>

		<div class="slider__controls">
			<a href="#" class="slider__controls-button slider_controls-button_prev">prev</a>
			<a href="#" class="slider__controls-button slider_controls-button_next">next</a>
		</div>

		<!-- slider - end -->

		<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vero perferendis porro quos, sapiente quod dolores nam voluptatum at quibusdam ipsa odio placeat sequi, officia similique quae libero quo esse numquam! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nam, magni tenetur a eos quibusdam laboriosam ut, molestias cum velit voluptatibus libero ea cupiditate harum. Ipsum est aperiam aspernatur praesentium nisi!</p>

	</div>

<script src="js/jquery-1.11.3.js"></script>
<script src="js/main.js"></script>
</body>
</html>


.clearfix:before, .clearfix:after{
	content: " ";
	display: table;
}
.clearfix:after{
	clear: both;
}

div.slider {
	max-width: 600px;
	height: 338px;
	margin: auto;
	/*background: #F6F6F6;*/
	/*overflow: hidden;*/

	padding: 10px;
	border: 1px solid #359FBC;
	background: #fff;
}
div.slider__list--wrap {
	max-width: 600px;
	height: 338px;
	overflow: hidden;
}
ul.slider__list {
	margin: 0;
	padding: 0;
	position: relative;
	width: 100%;
}
li.slider__item {
	display: block;
	position: absolute; 
	top: 0;
	left: 0;
	/* z-index: 0; */
	width: 100%;
}
.active {
	position: relative;
	z-index: 1;
}
.inslide {
	z-index: 2;
}
img {
	width: 100%;
	display: block;
}

/* точки */

li.slider__dots-item {
	display: block;
	width: 20px;
	height: 20px;
	border-radius: 50%;
	background: #FF7055;
	margin-left: 8px;
	float: left;
	position: relative;
}
a.slider__dots-link {
	display: block;
	width: 18px;
	height: 18px;
	border-radius: 50%;
	background: #fff;
	position: absolute;
	top: 50%;
	left: 50%;
	margin-top: -9px;
	margin-left: -9px;
}
.active_dot a {
	background: #359FBC;
}


$(function() {

	var flag = true, 
		timer,
		timerDuration = 6000;

	var init = function() {
		
		// создаем динамически точки
		createDots();

		// включим автопереключение
		autoSwitch();

		$('.slider__controls-button').on('click', function(e) {
			e.preventDefault();

			var
				$this = $(this),
				slides = $(".slider__item"), // li
				activeSlide = slides.filter(".active"),
				nextSlide = activeSlide.next(),
				prevSlide = activeSlide.prev(),
				firstSlide = slides.first(),
				lastSlide = slides.last();

			clearTimer();

			if ($this.hasClass('slider_controls-button_next')) {
				if(nextSlide.length) { // закольцовываем
					moveSlide(nextSlide, 'forward');
				} else {
					moveSlide(firstSlide, 'forward');
				}
			}
			else {
				if(prevSlide.length) { // закольцовываем
					moveSlide(prevSlide, 'backward');
				} else {
					moveSlide(lastSlide, 'backward');
				}
			}

		});

		// клик по точкам
		$('a.slider__dots-link').on('click', function(e) {
			e.preventDefault();

			var 
				$this = $(this),
				activeSlide = $('.active');
				dots = $this.closest('.slider__dots').find('.slider__dots-item'),
				activeDot = dots.filter('.active_dot'),
				dot = $this.closest('.slider__dots-item'), // текущая точка
				curDotNum = dot.index(),
				direction = (activeDot.index() < curDotNum) ? 'forward' : 'backward',
				reqSlide = $('.slider').find('.slider__item').eq(curDotNum);

			if (curDotNum === activeSlide.index()) {
		
			} else {
				clearTimer();
				moveSlide(reqSlide, direction);
			}

		});
	}

	var moveSlide = function(slide, direction) {

		var 
			container = $('.slider'),
			slides = container.find('.slider__item'), // li
			activeSlide = slides.filter('.active'); // активный слайд
			slideWidth = slides.width(),
			duration = 500,
			reqCssPosition = 0, // положение, в которое должен придти слайд
			reqSlideStrafe = 0;

		if (flag) {

			flag = false;

			// если у нас напрвление анимации вперед, то положение в которое
			// мы должны привести наш слайд - slideWidth
			if (direction === "forward") {
				reqCssPosition = slideWidth;
				reqSlideStrafe = -slideWidth;
			} 
			else if (direction == "backward") {
				reqCssPosition = -slideWidth;
				reqSlideStrafe = slideWidth;
			}

			slide.css('left', reqCssPosition).addClass('inslide');

			var movableSlide = slides.filter('.inslide');

			activeSlide.animate({left: reqSlideStrafe}, duration);
			movableSlide.animate({left: 0}, duration, function() {
				slides.css('left', '0').removeClass('active');
				$(this).toggleClass('inslide active');

				// функция, отвечающая за переключение слайдов стрелками
				setActiveDot();

				flag = true;
			});
		}
	}

	// динамическое создание точек
	var createDots = function() {
		var 
			container = $('.slider');

		var dotMarkup = '<li class="slider__dots-item">\
							<a class="slider__dots-link" href="#"></a>\
						 </li>';

		container.each(function() {
			var 
				$this = $(this),
				slides = $this.find('.slider__item'),
				// dotContainer = $this.find('.slider__dots');
				dotContainer = $('.slider__dots');

			for (var i = 0; i < slides.size(); i++) {
				dotContainer.append(dotMarkup);
			}

			setActiveDot();
		});
	}

	var setActiveDot = function() {
		var 
			slides = $('.slider__list--wrap').find('.slider__item'); // все наши слайды

		// точка, которая по своей позиции соответствует позиции активного слайда в наборе всех слайдов - .index()
		$('.slider__dots-item').eq(slides.filter('.active').index())
			.addClass('active_dot').siblings().removeClass('active_dot');
	}

	var autoSwitch = function() {
		var 
			_this = this;

		timer = setInterval(function() {
			var slides = $('.slider__item'),
				activeSlide = slides.filter('.active'),
				nextSlide = activeSlide.next(),
				firstSlide = slides.first();

			if(nextSlide.length) { // закольцовываем
				moveSlide(nextSlide, 'forward');
			} else {
				moveSlide(firstSlide, 'forward');
			}

		}, timerDuration);
	}

	var clearTimer = function() {
		if (timer) {
			clearInterval(timer);
			autoSwitch();
		}
	}

	// if ($('.slider') != undefined) init();
	if ($('.slider'.length) != undefined) init();
});
Ответить с цитированием