// 列表布局,图片左浮动,外侧容器设置overflow:hidden;
// 组合使用构造函数模式(对象不共享的数据)和原型模式(对象共享的数据)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="utf-8"> 5 <style type="text/css" media="screen"> 6 * { margin:0; padding:0; font-size: 14px;} 7 .slider { width:550px; height:200px; margin:50px auto 0; overflow: hidden;} 8 .slider ul { width:10000px; list-style:none; } 9 .slider li { float: left; } 10 .slider li img { width:550px; text-align: center;} 11 #slider-nav { width:550px; margin:30px auto; text-align: center;} 12 #slider-nav button { height:34px; line-height: 34px; width:75px; text-align: center; cursor:pointer; margin:0 20px;} 13 </style> 14 </head> 15 <body> 16 <div class="slider"> 17 <ul> 18 <li><img src="http://www.gbtags.com/gb/networks/uploads/afb73f09-8334-46b2-ad66-4abeb7c67a0a/images/gbtags1.jpg" alt="image"></li> 19 <li><img src="http://www.gbtags.com/gb/networks/uploads/afb73f09-8334-46b2-ad66-4abeb7c67a0a/images/gbtags2.jpg" alt="image"></li> 20 <li><img src="http://www.gbtags.com/gb/networks/uploads/afb73f09-8334-46b2-ad66-4abeb7c67a0a/images/gbtags3.jpg" alt="image"></li> 21 <li><img src="http://www.gbtags.com/gb/networks/uploads/afb73f09-8334-46b2-ad66-4abeb7c67a0a/images/gbtags4.jpg" alt="image"></li> 22 </ul> 23 </div> 24 25 <div id="slider-nav"> 26 <button data-direction="prev">« 上一个</button><button data-direction="next">下一个 »</button> 27 </div> 28 </body> 29 <script src="http://cdn.gbtags.com/jquery/2.1.1/jquery.min.js"></script> 30 <script> 31 32 function Slider(container,nav){ // 构造Slider()函数; 33 this.container = container; // 定义一系列局部变量; 34 this.nav = nav; 35 this.imgs = this.container.find(‘img‘); 36 this.imgWidth = this.imgs[0].width; 37 this.imgsLen = this.imgs.length; 38 this.current = 0; 39 }; 40 41 Slider.prototype.transition = function(){ // 使用prototype来定义transition()方法; 42 this.container.animate({ // 编写外包围容器(ul)的运动方向及运动长度; 43 ‘margin-left‘:-(this.current*this.imgWidth) 44 }); 45 }; 46 47 Slider.prototype.setCurrent = function(dir){ // 使用prototype来定义setCurrent()方法; 48 var pos = this.current; 49 pos += (~~(dir === ‘next‘) || -1); // 使用"~~"进行类型转换,转换成数字类型; ~~true == 1; ~~false == 0; 50 this.current = (pos < 0) ? this.imgsLen - 1 : pos % this.imgsLen; 51 return pos; 52 }; 53 54 $(function(){ 55 var container = $(‘.slider‘).children(‘ul‘), // 定义container变量的值; 56 slider = new Slider(container, $(‘#slider-nav‘)); // 实例化Slider()函数并传参; 57 58 slider.nav.find(‘button‘).on(‘click‘,function(){ // 找到触发按钮并绑定事件; 59 slider.setCurrent($(this).data(‘direction‘)); // 调用setCurrent()函数并传入按钮的data-direction的值; 60 slider.transition(); // 调用transition()方法,使幻灯片运动; 61 }) 62 }); 63 64 </script> 65 </html>
时间: 2024-10-10 02:09:05