您所在的位置:小祥子 » 编程 » JavaScript » 正文

JavaScript--水平幻灯片

时间:2015-05-28 编辑:翌子涵 来源:本站整理

// 列表布局,图片左浮动,外侧容器设置overflow:hidden;

// 组合使用构造函数模式(对象不共享的数据)和原型模式(对象共享的数据)



 <!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="utf-8">
     <style type="text/CSS" media="screen">
         * { margin:0; padding:0; font-size: 14px;}
         .slider { width:550px; height:200px; margin:50px auto 0; overflow: hidden;}
         .slider ul { width:10000px; list-style:none; }
         .slider li { float: left; }
         .slider li img { width:550px; text-align: center;}
         #slider-nav { width:550px;  margin:30px auto; text-align: center;}
         #slider-nav button { height:34px; line-height: 34px; width:75px; text-align: center; cursor:pointer; margin:0 20px;}
     </style>
 </head>
 <body>
     <div class="slider">
         <ul>
             <li><img src="/article/UploadPic/2015-5/20155282105954.jpg" alt="image"></li>
             <li><img src="/article/UploadPic/2015-5/20155282105559.jpg" alt="image"></li>
             <li><img src="/article/UploadPic/2015-5/20155282105799.jpg" alt="image"></li>
             <li><img src="/article/UploadPic/2015-5/20155282105547.jpg" alt="image"></li>
         </ul>
     </div>
      
     <div id="slider-nav">
         <button data-direction="prev">« 上一个</button><button data-direction="next">下一个 »</button>
     </div>
 </body>
     <script src="http://cdn.gbtags.com/jquery/2.1.1/jquery.min.JS"></script>
     <script>
 
     function Slider(container,nav){                             // 构造Slider()函数;
         this.container = container;                             // 定义一系列局部变量;
         this.nav = nav;
         this.imgs = this.container.find('img');
         this.imgWidth = this.imgs[0].width;
         this.imgsLen = this.imgs.length;
         this.current = 0;
     };
 
     Slider.prototype.transition = function(){                   // 使用prototype来定义transition()方法;
         this.container.animate({                                // 编写外包围容器(ul)的运动方向及运动长度;
             'margin-left':-(this.current*this.imgWidth)
         });
     };
 
     Slider.prototype.setCurrent = function(dir){                // 使用prototype来定义setCurrent()方法;
         var pos = this.current;
         pos += (~~(dir === 'next') || -1);                      // 使用"~~"进行类型转换,转换成数字类型; ~~true == 1; ~~false == 0;
         this.current = (pos < 0) ? this.imgsLen - 1 : pos % this.imgsLen;
         return pos;
     };
 
     $(function(){
         var container = $('.slider').children('ul'),            // 定义container变量的值;
             slider = new Slider(container, $('#slider-nav'));   // 实例化Slider()函数并传参;
 
         slider.nav.find('button').on('click',function(){        // 找到触发按钮并绑定事件;
             slider.setCurrent($(this).data('direction'));       // 调用setCurrent()函数并传入按钮的data-direction的值;
             slider.transition();                                // 调用transition()方法,使幻灯片运动;
         })
     });
 
     </script>
 </html>
关键词:水平 幻灯片