为了账号安全,请及时绑定邮箱和手机立即绑定

使用原生AngularJs模拟京东首页轮播图(不依靠任何外部插件)

标签:
AngularJS

效果图就这样,主要功能都实现了。


700

捕获.JPG

晚上决定要用原生angularjs写一个轮播图,体验一下AngularJs的魅力,其实写一个轮播图还是蛮简单的,我想了两种种方法,来实现轮播图(实际上细分是5种,但是其中两种是操作dom原生,三种是利用AngularJs的动画,所有归为两大类),等我写出来,大家好好理解一下就好。
那我先写一种,第一种是不使用angularjs的动画模块,只使用指令来完成动画的切换。在这里面就是在指令里操作dom元素,超级easy。
不说了上code。

<!DOCTYPE html><html lang="en" ng-app="lunbo"><head>
    <meta charset="UTF-8">
    <script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="lib/angular.min.js" type="text/javascript"></script>
    <script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="lib/angular-animate.js" type="text/javascript"></script>
    <title></title>
    <style>
        .hidden{            display: none;
        }        .active{            display: block;
        }    </style></head><body ng-controller="lunboController">
    <div lunbo ></div>
    <script type="text/ng-template" id="lunbo.html">
        <ul>
            <li ng-repeat="img in images"
                class="fade-in style hidden" >
                <a href="{{img.href}}"><img class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="{{img.src}}" alt=""/></a></li>
        </ul>
    </script></body><script>
    var app=angular.module('lunbo',['ngAnimate']);
    app.controller('lunboController',['$scope','readJSON', function ($scope,readJSON) {

    }]);
    app.factory('readJSON',['$http','$q', function ($http,$q) {        return {            query: function () {                var deferred=$q.defer();
                $http({                    method:'GET',                    url:'img.json'
                }).success(function (data, status, header, config) {
                    deferred.resolve(data);
                }).error(function (data, status, header, config) {
                    deferred.reject(data);
                });                return deferred.promise;
            }
        }
    }]);
    app.directive('lunbo',['readJSON', function (readJSON) {        return{            restrict:'EA',            templateUrl:'lunbo.html',            scope:{},            link: function (scope, element, attr) {                var promise=readJSON.query();                var step=0;
                scope.flag=false;
                promise.then(function (data) {                    console.log(data);
                    scope.images=data;
                });
                setInterval(function () {
                    element.find("li").css({"display":"none","opacity":0});
                    step++;
                    step=step%5;
                    element.find("li").eq(step).css({"display":"block","opacity":1});
                },1000)
            }
        }
    }]);    /*app.animation('.fade-in', function () {
        return{
            enter: function (element, done) {

            }
        }
    })*/</script></html>
[
  {    "href":"http://www.google.com",    "src":"img/5.jpg",    "alt":"5"
  },
  {    "href":"http://www.google.com",    "src":"img/6.jpg",    "alt":"6"
  },
  {    "href":"http://www.google.com",    "src":"img/7.jpg",    "alt":"7"
  },
  {    "href":"http://www.google.com",    "src":"img/8.jpg",    "alt":"8"
  },
  {    "href":"http://www.google.com",    "src":"img/9.jpg",    "alt":"9"
  }
]

看指令的最后是不是很简单啊,就是通过指令的link函数中的element对象调用angularjs自身封装的jquery函数来完成的。另外一种是

link: function (scope, element, attr) {                var promise=readJSON.query();                var step=0;
                scope.flag=false;
                promise.then(function (data) {                    console.log(data);
                    scope.images=data;
                });
                setInterval(function () {
                    element.find("li").removeclass("acitve");
                    step++;
                    step=step%5;
                    element.find("li").eq(step).addclass("active");
                },1000)
            }
  }

如果要过渡效果,可以在acive类中加入css3的过渡动画。

这里面是用$http和$q来实现了一个延迟异步拉取数据,通过这样组合函数可以使函数功能更加健壮,也更方便监控函数。我以后会花时间专门来解释angularjs的$q和jquery的$Deferred的内容,其实原理差不多,都实现了promise操作。
接下来我会更新使用ngAnimate动画模块的方法,但是我也写一种利用JavaScript的方法,css3的可以参看我前面写的几篇关于angularjs动画模块的博客。
用JavaScript的实现方法的难点,在于如何实现元素的增加和减少,这样才能触发AngularJs的动画效果。这次写了一个,但是在开始运行的时候有个小瑕疵,就是小按钮的步长一定要加上1,才和照片同步。不知道怎么造成的,以后再来填坑,如有不妥的地方,欢迎指出。

还有一种写法,我不太推荐,虽然很好写,我把思路大概说一下,就是建立一个数组,用来存放图片的src等信息,每次从里面取出一个,用双向绑定到img的src上,当下现读取img,当到下一个的时候,把img的src清空,并且赋值下一个。以此循环,这样虽然也可以做到轮播,但是这样极大的增加了http请求数量,在网速低的情况下,体验很不好,我不推荐。
所有我很推荐我这种写法,虽然啰嗦点,但是体验好啊。

<!DOCTYPE html><html lang="en" ng-app="lunbo"><head>
    <meta charset="UTF-8">
    <script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="lib/angular.min.js" type="text/javascript"></script>
    <script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="lib/angular-animate.js" type="text/javascript"></script>
    <title></title>
    <style>
        *{            padding: 0px;            margin: 0px;
        }        div {            position: relative;
        }        div ul {            position: absolute;
        }        div ul li {            list-style-type: none;            position: absolute;
        }        div ul li a img {            display: block;            width: 730px;            height: 454px;
        }        div ul.listContent{            position: absolute;            left: 500px;            top: 410px;            width: 200px;            height: 25px;
        }        div ul.listContent li.list{            position: relative;            display: block;            width: 25px;            height: 25px;            float: left;            margin: 0 5px;            border: 1px solid blue;            text-align: center;            line-height: 25px;            cursor: pointer;
        }        .active{            background: #161616;            color: #ffffff;
        }    </style></head><body ng-controller="lunboController"><div lunbo ></div><script type="text/ng-template" id="lunbo.html">
        <div ng-mouseleave="start()">
            <ul ng-switch="pic">
                <li ng-switch-when="0" class="fade-in "><a href="{{img1.href}}"><img class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="{{img1.src}}" alt=""/></a></li>
                <li ng-switch-when="1" class="fade-in "><a href="{{img2.href}}"><img class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="{{img2.src}}" alt=""/></a></li>
                <li ng-switch-when="2" class="fade-in "><a href="{{img3.href}}"><img class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="{{img3.src}}" alt=""/></a></li>
                <li ng-switch-when="3" class="fade-in "><a href="{{img4.href}}"><img class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="{{img4.src}}" alt=""/></a></li>
                <li ng-switch-when="4" class="fade-in "><a href="{{img5.href}}"><img class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="{{img5.src}}" alt=""/></a></li>
            </ul>
            <ul class="listContent" >
                <li class="list" ng-click="clickEvent(0)" >1</li>
                <li class="list" ng-click="clickEvent(1)" >2</li>
                <li class="list" ng-click="clickEvent(2)" >3</li>
                <li class="list" ng-click="clickEvent(3)" >4</li>
                <li class="list" ng-click="clickEvent(4)" >5</li>
            </ul>
        </div></script></body><script>
    var app=angular.module('lunbo',['ngAnimate']);
    app.controller('lunboController',['$scope','readJSON','mouseEvent' ,function ($scope,readJSON,mouseEvent) {

    }]);
    app.factory('readJSON',['$http','$q', function ($http,$q) {        return {
            query: function (){                var deferred=$q.defer();
                $http({
                    method:'GET',
                    url:'img.json'
                }).success(function (data, status, header, config) {
                    deferred.resolve(data);
                }).error(function (data, status, header, config) {
                    deferred.reject(data);
                });                return deferred.promise;
            }
        }
    }]);    /*这个服务有问题,需改进,暂时没想到解决办法*/
    app.factory('mouseEvent', function () {       return{
           mouseevent: function (ele1,ele2 ,event, done) {


           }
       }
    });
    app.directive('lunbo',['readJSON','$timeout','mouseEvent' ,function (readJSON,$timeout,mouseEvent) {        return{
            restrict:'EA',
            templateUrl:'lunbo.html',
            scope:{},
            link: function (scope, element, attr) {                var promise=readJSON.query();                var step=0;                var time=null;

                promise.then(function (data) {
                    scope.img1=data[0];
                    scope.img2=data[1];
                    scope.img3=data[2];
                    scope.img4=data[3];
                    scope.img5=data[4];
                });                var stepFun= function () {
                    element.find("li").removeClass("active");
                    element.find("li").eq(step+1).addClass("active");
                    scope.pic=step;
                    step++;
                    step=step%5;
                    time=$timeout(function () {
                        stepFun();
                    },5000);
                };
                stepFun();                /*点击事件*/
                scope.clickEvent= function (number) {
                    scope.pic=number;
                    element.find("li").removeClass("active");
                    element.find("li").eq(number+1).addClass("active");
                    $timeout.cancel(time);
                    step=number;
                };                /*鼠标移除动画重新开始*/
                scope.start= function () {
                    $timeout.cancel(time);
                    stepFun();
                }
            }
        }
    }]);
    app.animation('.fade-in', function () {        return{
            enter: function (element, done) {                var step=0;                var time=null;//计时器
                var animationFunc= function () {
                    step+=20;                    if(step>100){
                        done();
                        clearInterval(time);
                    }else{
                        element.css("opacity",step/100);
                    }
                };
                element.css("opacity",0);
                time=setInterval(animationFunc,50);
            },
            leave: function (element,done) {                var step=100;                var time=null;                var animationFun= function () {
                    step-=20;                    if(step<0){
                        done();
                        clearInterval(time);
                    }else{
                        element.css("opacity",step/100)
                    }
                };
                element.css("opacity",1);
                time=setInterval(animationFun,40);
            }
        }
    })</script></html>

还有一种写法,我不太推荐,虽然很好写,我把思路大概说一下,就是建立一个数组,用来存放图片的src等信息,每次从里面取出一个,用双向绑定到img的src上,当下现读取img,当到下一个的时候,把img的src清空,并且赋值下一个。以此循环,这样虽然也可以做到轮播,但是这样极大的增加了http请求数量,在网速低的情况下,体验很不好,我不推荐。
所有我很推荐我这种写法,虽然啰嗦点,但是体验好啊。



作者:MakingChoice
链接:https://www.jianshu.com/p/9b6a6180f9f1


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消