JS+jQuery实现渐隐渐现轮播图:模拟服务器获取图片数据

我前面写过简易版轮播图:简易轮播图
也写过无缝连接的轮播图:无缝连接轮播图

现在是实现渐隐渐现的轮播图,它与前面两个轮播图的区别是:不是左右滑动,而是所有的图片重叠,单张渐隐渐现。利用的是CSS中的z-index和opacity两个属性,需要显示的图片的z-index和opcacity都为1,其余图片的z-index和opcacity都为0。

html部分:index.html

<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<title>渐隐渐现轮播图</title>
	<!-- IMPORT CSS -->
	<link rel="stylesheet" href="css/reset.min.css">
	<link rel="stylesheet" href="css/banner.css">
</head>

<body>
	<div class="container">
		<div class="wrapper">
			<!-- <div class="slide">
				<img src="0.jpg" alt="">
			</div> -->
		</div>

		<!-- 分页器 -->
		<div class="pagination">
            <!-- <span class="active"></span>
            <span></span> -->
        </div>

		<!-- 左右按钮 -->
		<a href="javascript:;" class="button-prev"></a>
		<a href="javascript:;" class="button-next"></a>
	</div>

	<!-- IMPORT JS -->
    <script src="jquery-1.11.3.min.js"></script>
    <script src="js/index.js"></script>

</body>

</html>

CSS部分:banner.css

.container{
    box-sizing: border-box;
    margin: 20px auto;
    width: 500px;
    height: 260px;
    overflow: hidden;
    position: relative;
}
.container .wrapper{
    width: 100%;
    height: 100%;
    position: relative;
}
.container .wrapper .slide{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    /* 所有的slide样式 */
    z-index: 0;
    opacity: 0;
}
/* 默认展示第一个 */
.container .wrapper .slide:nth-child(1){
    z-index: 1;
    opacity: 1;
}
.container .wrapper .slide img{
    width: 100%;
    height: 100%;
}

.container .pagination{
    position: absolute;
    right: 20px;
    bottom: 20px;
    z-index: 999;
    font-size: 0;
}
.container .pagination span{
    display: inline-block;
    width: 10px;
    height: 10px;
    background: rgba(0, 0, 0, .4);
    border: 2px solid rgba(255, 255, 255, .4);
    border-radius: 50%;
    margin: 0 4px;
}
.container .pagination span.active{
    background: rgb(255, 255, 255, .4);
    border-color: rgba(0, 0, 0, .4);
}
.container .button-prev,
.container .button-next{
    position: absolute;
    top: 50%;
    margin-top: -35px;
    z-index: 999;
    width: 40px;
    height: 70px;
    background: url("../icon-slides.png") no-repeat;
}
.container .button-prev{
    left: 0;
    background-position: -83px 0;
}
.container .button-prev:hover{
    background-position: 0 0;
}
.container .button-next{
    right: 0;
    background-position: -124px 0;
}
.container .button-next:hover{
    background-position: -41px 0;
}

JS部分:index.js
注:throttle函数的功能是节流,目的是防止图片快速切换产生的图片混乱。

function throttle(func, wait) {
	let timer = null,
		result = null,
		previous = 0;
	return function anonymous(...args) {
		let context = this,
			now = new Date,
			spanTime = wait - (now - previous);
		if (spanTime <= 0) {
			result = func.call(context, ...args);
			clearTimeout(timer);
			timer = null;
			previous = now;
		} else if (!timer) {
			timer = setTimeout(() => {
				result = func.call(context, ...args);
				timer = null;
				previous = new Date;
			}, spanTime);
		}
		return result;
	}
}

let bannerModule = (function() {
    let $container = $('.container'),
		$wrapper = $container.find('.wrapper'),
		$pagination = $container.find('.pagination'),
		$buttonPrev = $container.find('.button-prev'),
		$buttonNext = $container.find('.button-next'),
		$slideList = null,
		$paginationList = null;

    let _data = null,
        autoTimer = null,
        interval = 2000,
        speed = 600, //每次切换图片需要的总时间
        imgIndex = 0, //当前显示图片的索引
        imgCount = 0; //图片的数量

    // 获取数据
    let queryData = function(callBack) {
        $.ajax({
            url: 'json/bannerData1.json',
            method: 'GET',
            async: true, //异步
            success: function(result) {
                // typeof callBack === 'function' ? callBack(result) : null;
                //=>
                callBack && callBack(result);
            }
        });
    };

    // 数据绑定
    let bindHTML = function(data) {
        let str1 = ``,
            str2 = ``;
        data.forEach((item, index) => {
            str1 += `<div class="slide">
                        <img src="${item.pic}" alt="">
                    </div>`;
            str2 += `<span class="${index === 0 ? 'active' : ''}"></span>`;
        });
        $wrapper.html(str1);
        $pagination.html(str2);

        // 获取结构内容
        $slideList = $wrapper.children('.slide');
        $paginationList = $pagination.children('span');
    };

    // 实现图片切换(很多地方都会用到,所以做成函数)
    let changeImg = function() {
        let $active = $slideList.eq(imgIndex),
            $siblings = $active.siblings();

        /* JS实现渐隐渐现动画:
        $active.css('z-index', 1);
        $siblings.css('z-index', 0);
        $active.stop().animate({
            opacity: 1
        }, speed, () => {
            $siblings.css('opacity', 0);
        });*/

        // CSS3实现渐隐渐现动画:
        $active.css('transition', `opacity ${speed}ms`);
        $siblings.css('transition', `opacity 0ms`);
        $active.css('z-index', 1);
        $siblings.css('z-index', 0);
        $active.css('opacity', 1).on('transitionend', function(){
            /* transitionend:当CSS3过渡动画结束后触发的事件,特殊注意的是,
            如果是多个样式执行了过渡效果,则当前事件被触发多次*/
            $siblings.css('opacity', 0);
        });
        dotsFocus();
    };

    // 自动轮播
    let autoPlay = function() {
        imgIndex ++;
        // 累加到边界,则从头开始
        if(imgIndex >= imgCount) {
            imgIndex = 0;
        }

        changeImg();
    };

    // 焦点自动对齐
    let dotsFocus = function() {
        $paginationList.each((index, item) => {
            let $item = $(item);
            if(index === imgIndex) {
                $item.addClass('active');
                return;
            }
            $item.removeClass('active');
        });
    };

    // 点击焦点对齐
    let clickDots = function() {
        $paginationList.click(throttle(function() {
            imgIndex = $(this).index();
            changeImg();
        }, 500));
    }

    // 点击左右按钮
    let clickBtn = function() {
        $buttonNext.click(throttle(autoPlay, 300));

        $buttonPrev.click(throttle(function() {
            imgIndex --;
            // 累加到边界
            if(imgIndex < 0) {
                imgIndex = imgCount - 1;
            }

            changeImg();
        }, 500));
    };

    return {
        init: function() {
            /*AJAX采用异步编程,我们需要在获取到数据后,才能进行数据绑定,
            轮播图处理等事情,此时我们可以基于回调函数来完成这件事情*/
            queryData(function anonymous(data) {
                // data就是服务器获取的数据
                bindHTML(data);
                imgCount = data.length;
                // 自动轮播
                autoTimer = setInterval(autoPlay, interval);
                clickDots();
                clickBtn();
            });

            // 这段代码可以放在init里边,也可以放外边,因为下面的操作要先获取数据
            // 鼠标进入/离开轮播区域时停止/开启自动轮播
            $container.mouseenter(function() {
                clearInterval(autoTimer);
            }).mouseleave(function() {
                autoTimer = setInterval(autoPlay, interval);
            });
        }
    }
})();

bannerModule.init();

模拟服务器的JSON数据:bannerData1.json

[{
	"id": 1,
	"pic": "0.jpg"
}, {
	"id": 2,
	"pic": "1.jpg"
}, {
	"id": 3,
	"pic": "2.jpg"
}, {
	"id": 4,
	"pic": "3.jpg"
}, {
	"id": 5,
	"pic": "4.jpg"
}]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值