<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js回调函数</title>
</head>
<body>
<script>
/*回调函数:一个函数当做参数传递给另外一个函数,这个被传递的函数就是回调函数*/
/*1.最基本的回调函数*/
/***************************************/
function funA() {
console.log("我是函数funA");
}
function funB(callback) {
console.log("我是函数funB");
/*当用户传入了回调函数,就执行这个回调函数*/
callback && callback();
}
/*调用回调函数*/
funB(funA);
/*在这里回调函数funA作为参数,传入funB函数中,funA函数在funB中执行了*/
//我是函数funB
//我是函数funA
/*************************************************/
/*2.匿名回调函数*/
function funC(callback) {
callback && callback();
}
/*调用函数funC,即funC(callback),传入一个匿名函数*/
func(function () {
console.log("我是一个匿名的回调函数");
})
/*******************回调函数的一个应用************************/
/*
* 1.这是移动端首页轮播图,具有自动轮播及手触摸左滑右滑功能
* 2.在左滑,右滑的时候需要停止自动轮播的计时器,在左滑右滑执行完毕后,在添加自动轮播的定时器
* 3.将轮播图页面移动封装为一个imgMove(callback)的方法
*
* */
/*轮播图滑动的imgMove(callback)方法*/
function imgMove(callback) {
$ul.animate({
transform: "translateX(" + (-bannerWidth * index) + "px)"
}, 200, "ease", function () {
if (index >= 9) {
index = 1;
$(this).css({transform: "translateX(" + (-bannerWidth * index) + "px)"});
} else if (index <= 0) {
index = 8;
$(this).css({transform: "translateX(" + (-bannerWidth * index) + "px)"});
}
/*小圆点随着轮播图改变样式*/
$pointLis.removeClass("current").eq(index - 1).addClass("current");
/*如果传入了回调函数,说明执行了左滑或者右滑,回调函数重新添加定时器*/
callback && callback();
});
}
/*定时器,轮播图自动轮播,正常调用imgMove()不传入回调函数*/
var timer = setInterval(function () {
index++;
imgMove();
}, 1000);
/*手指触摸左滑,在滑动时需要清除定时器即停止自动轮播功能,在画完完成后通过回调函数重新添加定时器*/
$ul.on("swipeLeft", function () {
/*滑动前清除定时器*/
clearInterval(timer);
index++;
/*在滑动结束后添加定时器*/
imgMove(function () {
timer = setInterval(function () {
index++;
imgMove();
}, 1000);
});
});
/*手指触摸右滑*/
$ul.on("swipeRight", function () {
clearInterval(timer);
index--;
imgMove(function () {
clearInterval(timer);
timer = setInterval(function () {
index++;
imgMove();
}, 1000);
});
});
</script>
</body>
</html>