小金井にあるWEB制作会社の備忘録

MEMORANDUM

jQueryを使って簡単にスライドショーを実装

飲食店サイトを作成した際にしようした簡単なスライドショーの方法をメモ。
画像の切り替わりはフェードイン・フェードアウト方式。
速度も自由に変更可能。

HTML

<figure class="mainimageTop">
<ul>
<li class="active"></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</figure>

<script>
$(function() {
	setInterval('slideSwitch()', 5000 );
	//5000は次の画像に切り替わるまでのミリ秒
});
</script>

CSS

.mainimageTop{
	width: 100%;
	position: fixed;
	z-index: -1;
	top: 0;
	left: 0;
	overflow: hidden; }
.mainimageTop::after{
	content: '';
	width: 60%;
	height: 100%;
	display: block;
	background-image: -webkit-gradient(linear,left top,right top,from(rgba(0,0,0,0)),color-stop(0.78, rgba(0,0,0,1.0)),to(#000));
	background-image: -moz-linear-gradient(left,rgba(0,0,0,0),rgba(0,0,0,0.95) 78%,#000);
	position: absolute;
	top: 0;
	right: 0;
	z-index: 10; }
.mainimageTop ul li{
	width: 100%;
	height: 100%;
	box-sizing: border-box;
	position: absolute;
	top: 0;
	left: 0;
	margin: auto;
	z-index: 5; }
.mainimageTop ul li.active{
	z-index: 7; }
.mainimageTop ul li.next-active{
	z-index: 6; }
.mainimageTop ul li:nth-of-type(1){
	background: url(画像URL) center fixed;
	background-size: cover;
	-webkit-background-size: cover;
	-moz-background-size: cover; }
.mainimageTop ul li:nth-of-type(2){
	background: url(画像URL) center fixed;
	background-size: cover;
	-webkit-background-size: cover;
	-moz-background-size: cover; }
.mainimageTop ul li:nth-of-type(3){
	background: url(画像URL) center fixed;
	background-size: cover;
	-webkit-background-size: cover;
	-moz-background-size: cover; }
.mainimageTop ul li:nth-of-type(4){
	background: url(画像URL) center fixed;
	background-size: cover;
	-webkit-background-size: cover;
	-moz-background-size: cover; }
.mainimageTop ul li:nth-of-type(5){
	background: url(画像URL) center fixed;
	background-size: cover;
	-webkit-background-size: cover;
	-moz-background-size: cover; }

jQuery

function slideSwitch(){
	var $active = $('.mainimageTop ul li.active');
	if($active.length == 0 ) $active = $('.mainimageTop ul > li:last');
	var $next = $active.next().length ? $active.next() : $('.mainimageTop ul > li:first');
	$active.addClass('next-active');
	$next.css({opacity: 0.0})
	.addClass('active')
	.animate({opacity: 1.0},3000,function(){
		//3000は画像が表示されるまでにかかるミリ秒
		$active.removeClass('active next-active');
	});
};

同一カテゴリーの記事