不管是app端,还是web端,轮播图是永远少不了的,swiper是当前最流行的,使用最多的一个插件。
但是它有个问题,当我们请求完数据,直接在html中使用angularJs的for循环去创建轮播图,就会很卡,页面加载有问题,所有在这里我使用官方的appSlide来循环添加轮播图的图片。
首先就是导入js和css文件:
初始化swiper:
var swiper = new Swiper('.swiper-container-ad', {
pagination: '.swiper-pagination',
paginationClickable: true,
loop: true
});
有问题的方式(使用ng-repeat直接循环,swpier循环有问题):
解决方法一:
使用函数式编程的实体库Underscore.js,具体用法如下,先导入js文件
然后在html中写上你想要的UI样式,body后面写上你适配好的div控件,body及script内容如下:
在js中,我们将通过循环,将每一个model传进来
for(var i = 0; i < response.response.items.length; i++) {
$scope.item = response.response.items[i];
swiper.appendSlide(_.template($('#templateSwiper').html())($scope.item));
}
注:其中swiper是指初始化创建的对象,在html中,templateSwiper传入的是model,通过<%=属性%>来取值。
解决方法二:
这个方法适合不是很复杂的轮播图(我这里只轮播图片),通过html文本的循环添加到swiper中即可,代码如下:
// html中
// js中
$scope.images = [];
$scope.images.push("");
for(var i = 0; i < response.body.product_images.length; i++){
$scope.images.push("");
}
$scope.images.push("");
if(response.body.product_images.length > 1)
$scope.images.push("");
$("images").innerHTML = $scope.images.join("");
解决方法三:
通过数值替换来达到创建轮播的目的:
// 定义好展示的轮播图位置
// 将我们需要展示的div写好,所有需要赋值的地方,使用#1#依次标记
// 然后在js中,请求结束时,通过循环添加和替换
$("#swiperwrapper").html(""); // 先清空当前id中所有的html文本
for(var i = 0; i < response.body.array.length; i++){
swiper.appendSlide($("#swiperSlide").html();.replace("#1#", response.body.array[i].post_image).replace("#2#", response.body.array[i].user_avatar).replace("#3#", response.body.array[i].post_guid).replace("#4#", response.body.array[i].post_favorite).replace("#5#", response.body.array[i].post_name));
}
注,这里使用到了jquery的一点语法,需要导入jquery的js文件,以上就是我所能使用的三种解决方法。