图片滚动图片的效果
图片滚动图片的效果(不一样的实现思路)
需求 : 图片切换的时候下一屏不允许出现空白的项,换句话说就是 :
1、当移动的最后一屏移动的个数小于要展示的个数的时候 ,只移动(展示个数-最后一屏的个数的)差值。 举个例子: 每一屏都要展示7个,但总个数才10个,滚动到下一屏时候用户看到的还是7个,这个时候需要移动的是三个
这个效果是基于jQuery写的,只是想纪念下自己的学习 话不多说了,贴代码
1 ( function ( $ ){ 2 var slider = function ( elem , args ){ 3 this .config = $.extend({ 4 effect : 'x', // 效果 水平 - x 5 speed : 600 , // 动画速度 6 trigger : 'mouseenter', // 触发事件 7 callback : null , // 回调函数 8 view : 7 9 }, args || {} ); 10 11 this .history = []; // 记录移动的历史记录 12 this .index = 0 ; 13 this .el = elem; 14 this .length = this .el.find('li').length; // 记录总长度 15 this .width = this .el.find('li').eq(0).outerWidth(); // 记录每一个单项的宽度 16 this .init(); 17 } 18 slider.prototype = { 19 constructor : slider, 20 init : function (){ 21 this .bindEvents(); 22 }, 23 bindEvents : function (){ 24 this .prev(); 25 this .next(); 26 }, 27 prev : function (){ 28 this .el.find('[data-type="left"]').click( $.proxy( function (){ 29 30 if ( ! this .history.length ) return ; // 如果记录为空,证明没有进行移动过,所以直接return 31 32 this .index-- ; 33 var step = this .history.pop(); // 取最后的移动步骤 34 var move = step * this .width; // 算出移动宽度 35 this .el.find("ul").animate( { "left" : "+="+move+"px" } , this .config.speed ) 36 37 } , this )); 38 }, 39 next : function (){ 40 this .el.find('[data-type="right"]').click( $.proxy( function (){ 41 // 如果是当前的最后一页,直接return 42 if ( this .index == parseInt( this .length / this .config.view , 10 ) ){ 43 return ; 44 } 45 this .index++ ; 46 // 这个计算很重要 47 // 计算 ( 下一页 * view ) 展示个数是否大于总长度 : 好比当前在第一页 (1+1) *7 > 12(总长度) 48 // 则this.step 赋值为取余 ,也就是剩下要移动的个数 49 if ( this .config.view * ( this .index+1) > this .length ){ 50 this .step = this .length% this .config.view; 51 } else { 52 // 否则移动展示的个数 53 this .step = this .config.view; 54 } 55 // 记录移动的历史记录 56 this .history.push( this .step); 57 var move = -1 * this .step * this .width; 58 this .el.find("ul").animate( { "left" : "+="+move+"px" } , this .config.speed ) 59 60 } , this )); 61 } 62 } 63 64 $.fn.slider = function ( args ){ 65 return this .each( function (){ 66 var el = this ; 67 var plugins = new slider( $( el ) , args ); 68 $(el).data("slider" , plugins ); 69 }); 70 } 71 })(jQuery)
开始对这个实现没有好的想法,本来想利用一个变量记录当前的移动个数的,但是后面突然想到用数组来做这样子的处理,顿时感觉清晰了。
这个的实现重点是一个记录移动步骤的数组。向左移动的时候往数组里面push移动的步骤,向右移动的时候,从数组里面取最后一项 [].pop()。
这样子很好的实现了需求,做的比较粗糙,麻烦各位大神提点意见
标签: javascirpt , slider , 图片滚动
作者: Leo_wl
出处: http://HdhCmsTestcnblogs测试数据/Leo_wl/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
版权信息声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did45495