最近做一个web项目,站点首页需要像 百度统计 页面类似的切换横幅,有兴趣的可以先看看它的效果,这样就比较容易理解为什么我单独做个插件。其实类似的 jquery 插件网上类似的多的去了,随便网上下了两做了个demo 演示一下,效果不错吗!:) 我是在全屏的状态下看的,效果还行,当把屏幕切小之后问题就出来了,屏幕小了之后图片的后面部分显示不出来了,本来的效果应该是如果屏幕小了应该把图片两 边不重要的部分隐藏掉,但是由于网上的插件都是直接生成的 img 元素,我的网站页面body元素固定宽度,居中的,所以出现前面说的问题。

      怎么办呢,本来想在别的插件基础上改一下,后来看改动比较多,干脆自己写个算了,以后用起来也方便。

      我的思路是,首先要实现上面的效果不用 img 元素, 我选择了用 span 元素 给它添加背景图片,显示方式为 inline-block,这样比较容易。

      由于需要切换 span 定位方式为绝对定位,外面包一层 div容器 定位方式为 relative 这样在切换的时候只要把要显示的 span 设置为 display: block; ,其余的全部设置为 display: none; 切换就解决了。

      然后就是通用性问题,给插件留下灵活的配置项跟事件接口。想了想大概就需要几项吧。

  •  设置项
  1. 图片切换间隔时间
  2. 动画完成时间
  3. 是否自动切换
  •  事件接口
  1. 图片切换完成事件
  2. 切换到最后一张图片
  3. 插件加载完成

      思路理清了,下面奉上插件代码:

  1 /*
  2 * 横幅切换插件
  3 * 作者:     封浩
  4 * 创建日期: 2015-04-03
  5 * 版本:     v1.0
  6 */
  7 (function ($) {
  8     var mySlider = function (element, options) {
  9         var settings = $.extend({}, $.fn.switchImg.defaults, options);
 10         var variables = {
 11             currentIndex: 0,
 12             nextIndex: 0,
 13             total: 0, 
 14             paused: true, //当前切换状态是否停止
 15             imgHeight: 0,
 16             operation:"+"//控制移动方向
 17         }; 
 18         
 19         var slider = $(element);
 20 
 21         //图片切换容器
 22         var sliderContent = $('<div></div>').addClass('nivo-main').width(slider.width());
 23         //小圆点容器
 24         var controlNav = $('<div></div>').addClass('nivo-controlNav').attr("data-stop", "true");
 25         //左右切换按钮容器
 26         var btnContent = '<div class="nivo-NextContent"><a class="nivo-prevNav" data-opt="-">前进</a><a class="nivo-nextNav" data-opt="+">后退</a><div style="clear: both;"></div></div>';
 27 
 28         var bodyWidth = $("body").width();
 29         var dataDiv = slider.find("div:first-child");
 30         var self = this; 
 31         var images = dataDiv.find("img");
 32         images.each(function (i) {
 33             var child = $(this);
 34             var link = child.attr("data-link");
 35             var src = child.attr("src");
 36             var height = "0", active = "", display = 'inline-block';
 37             if (i == 0) {
 38                 variables.imgHeight = height = child.height() === 0 ? child.attr(height) : child.height();
 39                 active = "active";
 40             } else {
 41                 bodyWidth = 0;
 42                 display = "none";
 43             }
 44 
 45             if ($.trim(link) != "") {
 46                 sliderContent.append('<a href="' + link + '" target="_blank"><span style=\"background-image: url(' + src + '); width: ' + bodyWidth + 'px;position: Absolute;height:' + height + 'px;display:' + display + ';" data-bgImg="' + src + '"></span></a>');
 47             } else {
 48                 sliderContent.append('<span style=\"background-image: url(' + src + '); width: ' + bodyWidth + 'px;position: Absolute;height:' + height + 'px;display:' + display + ';" data-bgImg="' + src + '"></span>');
 49             }
 50             controlNav.append('<a class="nivo-control ' + active + '" rel="' + i + '">' + i + '</a>');
 51             variables.total++;
 52         });
 53         dataDiv.hide();
 54 
 55         //加载前事件
 56         settings.afterLoad();
 57         slider.append(btnContent);
 58         slider.append(sliderContent);
 59         slider.append(controlNav);
 60 
 61         $(window).resize(function () {
 62             var width = $("body").width();
 63             slider.children('.nav-main').width(width);
 64             sliderContent.find("span:eq(" + variables.currentIndex + ")").css({ width: width });
 65         });
 66 
 67         initEvent();
 68         var timer = 0;
 69         if (images.length > 1 && settings.autoStart) {
 70             initTime();
 71         }
 72 
 73         var toNext = function () {
 74             if (variables.nextIndex < 0) {
 75                 variables.nextIndex = variables.total - 1;
 76                 settings.lastSlide();
 77             } else if (variables.nextIndex > variables.total - 1) {
 78                 variables.nextIndex = 0;
 79                 settings.lastSlide();
 80             }
 81             var nextImg = sliderContent.find("span:eq(" + variables.nextIndex + ")");
 82             var currentImg = sliderContent.find("span:eq(" + variables.currentIndex + ")");
 83         
 84             sliderContent.find("span:eq(" + variables.nextIndex + ")").css({ height: variables.imgHeight, position: 'absolute', width: $("body").width(), top: 0, 'z-index': 4 });
 85 
 86             currentImg.stop(true, true);
 87             nextImg.stop(true, true);
 88 
 89             //淡入淡出效果
 90             currentImg.fadeOut(settings.animateTime);
 91             nextImg.fadeIn(settings.animateTime, settings.slideshowEnd);
 92             controlNav.find("a").removeClass("active");
 93             controlNav.find("a:eq(" + variables.nextIndex + ")").addClass("active");
 94             variables.currentIndex = variables.nextIndex;
 95         };
 96 
 97         //开始切换
 98         var switchStart = function (operator) {
 99             stop();
100             if (operator == "+") {
101                 variables.nextIndex = variables.currentIndex + 1;
102             } else if (operator == "-") {
103                 variables.nextIndex = variables.currentIndex - 1;
104             }
105             toNext();
106         }
107 
108         function initEvent() {
109             //小点
110             $(".nivo-control", slider).mouseover(function () {
111                 var index = parseInt($(this).attr("rel"));
112                 variables.nextIndex = index;
113                 switchStart("");
114             }).mouseout(function () {
115                 initTime(variables.operation);
116             });
117 
118             //图片
119             $("span", sliderContent).mouseout(function () {
120                 initTime(variables.operation);
121             }).mouseover(function () {
122                 stop();
123             });
124 
125             //上一张,下一张
126             $(".nivo-NextContent a", slider).click(function () {
127                 variables.operation = $(this).attr("data-opt");
128                 settings.autoStart = true;
129                 switchStart(variables.operation);
130             }).mouseout(function () {
131                 initTime(variables.operation);
132             });
133         }
134 
135         function initTime(operator) { 
136             if (variables.paused && settings.autoStart){
137                 timer = setInterval(function () {
138                     if (operator == "-") {
139                         variables.nextIndex--;
140                     } else {
141                         variables.nextIndex++;
142                     }
143                     toNext();
144                 }, settings.pauseTime);
145                 variables.paused = false; 
146             }
147         }
148         
149         var stop = function () {
150             clearInterval(timer);
151             variables.paused = true; 
152         };
153 
154         return this;
155     };
156 
157     $.fn.switchImg = function (options) {
158         return this.each(function () {
159             var element = $(this); 
160             if (element.data('data-switch')) return element.data('data-switch');
161             var switchObj = new mySlider(this, options);
162             element.data('data-switch', switchObj);
163         });
164     };
165 
166     
167     $.fn.switchImg.defaults = {
168         pauseTime: 3000,    //图片切换间隔时间
169         animateTime: 2000,  //动画完成时间 
170         autoStart: true,    //是否自动滚动
171         slideshowEnd: function () { }, //图片切换完成
172         lastSlide: function () { },    //切换到最后一张图片
173         afterLoad: function () { }     //插件加载完成
174     };
175     
176 })(jQuery);
View Code

相关文章: