一、新建src/js/carousel.es6文件,注意是es6后缀
/**
* Created by tcx on 2018/4/23.
*/
define(function (require, exports, module) {
let $ = require('jquery'); // 引用jquery
(function ($) {
let defaluts = {
large_elem: ".slide-bd",
small_elem: ".slide-hd",
left_btn: ".slide-prev",
right_btn: ".slide-next",
state: "slide-hd-item--on",
speed: "normal", // 速度
vis: 5, // 缩略图个数
autoplay: false // 自动播放
};
$.fn.extend({
"thumbnailImg": function (options) {
let opts = $.extend({}, defaluts, options); // options 覆盖默认参数
return this.each(function () {
let $this = $(this),
index,
currentIndex = -1,
l_mean,
length = $(opts.small_elem).find("ul li").length,
width = $(opts.small_elem).find("ul li").outerWidth(true);
// 初始化
$(opts.large_elem).find("ul li").eq(0).show();
$(opts.small_elem).find("ul li").eq(0).addClass(opts.state);
$(opts.small_elem).find("ul").css("width", length * width + "px");// 动态设置ul的宽度
// 等待的个数
if (length < opts.vis) {
l_mean = 0;
} else {
l_mean = ((parseInt(length / opts.vis) - 1) * opts.vis) + (length % opts.vis);
}
// 点击缩略图
$(opts.small_elem).find("ul li").click(function () {
index = $(this).index();
showImg(index);
});
/**
* 显示主体
* @param index 图片下标
*/
function showImg(index) {
$(opts.small_elem).find("ul li").eq(index).addClass(opts.state).siblings().removeClass(opts.state);
$(opts.large_elem).find("ul li").eq(index).fadeIn().siblings().hide();
let moveLength = index * width; // 当前图片距左总长度
let waitLength = l_mean * width;// 被遮住的等待项总长度
if (moveLength < waitLength) {
$(opts.small_elem).find("ul").stop().animate({
marginLeft: -moveLength + "px"
}, opts.speed)
} else {
$(opts.small_elem).find("ul").stop().animate({
marginLeft: -waitLength + "px"
}, opts.speed);
}
}
// 点击上一个
$(opts.left_btn).click(function () {
let index;
$(opts.small_elem).find("ul li").each(function (i) {
if ($(this).hasClass(opts.state)) {
index = i;
}
});
index--;
if (index < 0) {
index = length - 1;
}
currentIndex = index;
showImg(currentIndex);
});
// 点击下一个
$(opts.right_btn).click(function () {
let index;
$(opts.small_elem).find("ul li").each(function (i) {
if ($(this).hasClass(opts.state)) {
index = i;
}
});
index++;
if (index > length - 1) {
index = 0;
}
currentIndex = index;
showImg(currentIndex);
});
// 是否循环播放
if (opts.autoplay) {
let timer = setInterval(function () {
currentIndex++;
if (currentIndex > length - 1) {
currentIndex = 0;
}
showImg(currentIndex);
}, 2000);
// 悬浮停止
$this.hover(function () {
clearInterval(timer);
}, function () {
timer = setInterval(function () {
currentIndex++;
if (currentIndex > length - 1) {
currentIndex = 0;
}
showImg(currentIndex);
}, 2000);
})
}
})
}
});
})(jQuery);
});
二、config.js
在config.js中配置carousel.js
'carousel':'js/carousel.js'
三、src/js/main.es6
在main.es6中引入插件,以及配置参数
// 引入文件
require('carousel');
// 配置参数
$(".slide").thumbnailImg({
large_elem: ".slide-bd",
small_elem: ".slide-hd",
left_btn: ".slide-prev",
right_btn: ".slide-next",
autoplay:true
});
网友评论