简单的jQuery扩展函数-让函数缓冲执行
$.fn.retarder = function(delay, method) { var node = this; if (node.length) { if (node[0]._timer_) clearTimeout(node[0]._timer_); node[0]._timer_ = setTimeout(function() { method(node); }, delay); } return this; };
原理就是用了setTimeout这函数, 使用方法
$(div).retarder(150, function(i) { box.css({ height: box[0].hei - 50, width: box[0].wid, overflow: 'hidden' }); i.css(animate.from).stop(true, true).animate(animate.to, { duration: 200, complete: function() { if (!$.browser.msie) div.css('opacity', 1); box.css('display', 'none') } }) })
使用实例基于缓冲器做成的图片轮播渐显插件如下:
HTML
<div> <img src="/images/1.png" /> </div> <div> <img src="/images/2.png" /> </div> <div> <img src="/images/3.png" /> </div> <div> <img src="/images/4.png" /> </div> <div> <img src="/images/5.png" /> </div> </div>
jQuery
$.fn.initSlideshow = function () { var self = $(this); self.find("div").each(function (n) { var This = $(this); This.retarder(n * 2000, function (node) { node.fadeIn(1000, function () { if (n == self.find("div").length - 1) { /*self.find("div").fadeOut(1000).retarder(2000, function (node) { node.fadeIn(1000); });*/ self.find("div").retarder(5000, function (node) { node.fadeOut(1000); }); self.retarder(7000, function (node) { node.initSlideshow(); }); } }); }); }); };
CSS
#slideshow { width: 1040px; height: 345px; padding-left: 10px; } #slideshow div { float: left; height: 345px; line-height: 345px; display: none; }