图片轮播插件的设计抽象

提出需求
首页的轮播焦点图是个常见的需求。
需求是这样子的
1 每隔2秒切换一次图片
2 切换图片的时候,会对应显示该图片的说明
3 切换图片的时候,对应显示图片处于小按钮中的第几个,点击小按钮时跳到对应的大图
4 自动滚动图片,鼠标放到图片区域时,停止滚动,移出时继续
5 点击左右可以上下切换图片
对于做一个图片轮播并不难,按照要求,写代码就行。而如何设计一个通用的图片轮播组件确实需要好好思考。
因为样式是不确定的,同时html结构也是不确定的。所以问改如何设计这个轮播js呢?

使用插件?
我是反插件的,除非插件的代码足够简单和清晰。否则,使用插件后,以后的维护会有太多问题。当想改插件的某个功能时,会发现不可能了。

普通的方法

1 setInterval(function(){

2   scrollPicture()

3   showPictureNotice()

4   AddSlectedState()

5 },2000)

6 bind(left,right)

7 bind(selected)

大概意思就这样,每隔2秒,滚动图片,显示图片说明,给对应的小图片加选中状态
绑定左右事件,绑定选择小图片事件
这样写,结果是每次需求都要写一遍,麻烦


抽象
会发现每次滚动,其实都是一次帧的切换。然后出发对应的一系列操作。所以就抽出来的核心就是帧的切换操作

 1 function BaseFrameSwitch(o) {

 2     o = $.extend({

 3         interval : 3000,  //滚动间隔

 4         picNums : null  //图片张数

 5     }, o);

 6     this.para = o;  //参数

 7     this.intervalFunc = null;   //间隔函数

 8     this.seat = 1;      //现在的位置

 9     this.picNums = this.para.picNums;     //图片张数

10 }

11 

12 

13 BaseFrameSwitch.prototype = {

14     enterFrame : function() {

15         var me = this;

16         $.each(this.todo, function(a, b) {

17             b.apply(me, arguments);

18         });

19     },

20     leaveFrame: function() {

21         this.leaveCall && this.leaveCall.apply(this,arguments);

22     },

23     frame : function(a, b) {

24         this.leaveFrame();

25         if (a) {

26             if (a < 1 || a > this.picNums) {

27                 alert('input number from 1 to length of pictures');

28                 return false;

29             }

30             this.seat = a;

31         } else if (b) {

32             this.seat += b;

33             (this.seat === 0) && (this.seat = this.picNums);

34             (this.seat === this.picNums + 1) && (this.seat = 1);

35         }

36         this.enterFrame();

37     },

38     go : function() {

39         var me = this;

40         this.intervalFunc = setInterval(function() {

41             me.next();

42         }, this.para.interval);

43     },

44     stop : function() {

45         clearInterval(this.intervalFunc);

46     },

47     enter : function(i) {

48         this.frame(i);

49     },

50     next : function() {

51         this.frame(null, 1);

52     },

53     prev : function() {

54         this.frame(null, -1);

55     }

56 };

 

this.todo是需要添加的操作,貌似记得AS3中有个onEnterFrame,上面就是这个意思。
然后下面就是继承上面的baseFrame,而具体的不同实现在todo中去实现。
。。。

有点多,好像跟普通模式区别不大。。。
唯一的好处,就是不需要写切换的逻辑,只需要继承,并且有一些借口可以直接用。
写完这个,就感觉到,所谓的动画都是这种一帧帧的改变,就像fps游戏一样,每帧一次

这里是几个实例  http://www.riyue.me/plugin/slide/index.html

你可能感兴趣的:(图片轮播)