輪播圖制作主要思路:實現(xiàn)輪播圖滾動的效果,主要是使用animate()函數(shù)來實現(xiàn)這個過渡的動畫效果。當向左點擊時,畫面向右移動,應該把最后面的這個元素放在最前面,然后設置這個元素的父元素向左移動n個元素寬度,此時使用animate來恢復其距離原來的距離,已達到過渡的動畫效果。向右點擊則相反。
html:一個div包含一個ul,ul里面的li元素設置浮動,橫向展開。
js代碼模塊:
/*
*RollBox: 包含ul的直系父組件;Left(Right): 向左或向右點擊的標簽類或ID;Step:切換的個數(shù);Auto: 是否自動切換
*/
function acrossSwitch (RollBox, Left, Right, Step, Auto) {
var ThisStep = 1;? ? ? //切換個數(shù)
var ThisAuto = false;? //是否自動切換
var ThisSpeed = 500;? //播放一次動作速度
var PlayTime = 5000;? ? //自動切換速度
var RollUL = $(RollBox).find(">ul");
var RollBoxLi = RollUL.find(">li");
var LiWidth = RollBoxLi.outerWidth(true);
var LiLength = RollBoxLi.length;
RollUL.width(LiWidth * LiLength);
if (arguments[3]) ThisStep = Step;
if (arguments[4]) ThisAuto = Auto;
if (arguments[5]) ThisSpeed = Speed;
var MoveSize = LiWidth * ThisStep;
/*左右切換*/
function LeftRoll() {
for (i = 0; i < Step; i++) {
RollUL.find(">li:last").prependTo(RollUL);
}
RollUL.css({ "margin-left": -MoveSize });
RollUL.animate({ "margin-left": "0px" }, ThisSpeed);
}
function RightRoll() {
RollUL.animate({ "margin-left": -MoveSize }, ThisSpeed, function () {
for (i = 0; i < Step; i++) {
RollUL.find(">li:first").appendTo(RollUL);
}
RollUL.css({ "margin-left": "0px" });
});
}
$(document).on('click', '.channel-set', function(){
LeftRoll();
});
$(document).on('click', '.channel-ui', function(){
RightRoll();
});
$(Right).click(function () {
RightRoll();
});
$(Left).click(function () {
LeftRoll();
});
if (ThisAuto) {
var AutoPlay = setInterval(function () { RightRoll() }, PlayTime);
$(Right).hover(function () {
clearInterval(AutoPlay);
}, function () {
AutoPlay = setInterval(function () { RightRoll() }, PlayTime);
});
$(Left).hover(function () {
clearInterval(AutoPlay);
}, function () {
AutoPlay = setInterval(function () { RightRoll() }, PlayTime);
});
}
}