2010-07-08 98 views
0

我wahnt写一个jQuery插件,将改变x背景位置在一个循环的时间间隔。 $('#element').pluginName(); - 启动环形行动开始停止jquery插件

然后我wahnt通过$('#element').stopFunction();$('#element').pluginName().stopFunction();

是否有可能阻止它?你可以给我一个小费如何写它?



编辑(我的解决方案):

var LoadingAjax = function(element, options){ 
    var element = $(element); 
    var object = this; 
    var defaults = { 
      width: 30, 
      gap : 1, 
      interval : 100, 
      maxFrame: 8 
    }; 
    var settings = $.extend(defaults, options || {}); 
    var timer; 
    var frame = 1; 
    var is_loading; 

    // Public method 
    this.startAnimate = function(){ 
     console.log('start animate'); 
     is_loading = true; 
     timer = setTimeout(loop, settings.interval); 
    }; 
    this.stopAnimate = function(){ 
     console.log('stop animate'); 
     is_loading = false; 
     clearTimeout(timer); 
    }; 
    this.isLoading = function(){ 
     return is_loading; 
    } 
    // Private method 
    var loop = function(){ 
     console.log('frame: '+frame); 
     if(frame < defaults.maxFrame){ 
      element.css('background-position', '-'+(frame*(defaults.width+defaults.gap))+'px 0'); 
      frame++; 
     } 
     else{ 
      element.css('background-position', '0 0'); 
      frame = 1; 
     } 
     timer = setTimeout(loop, settings.interval); 
    }; 
}; 
$.fn.loadingAjax = function(options){ 
    return this.each(function(){ 
     var element = $(this); 
     // Return early if this element already has a plugin instance 
     if (element.data('loader')) return; 

     // pass options to plugin constructor 
     var plugin_instance = new LoadingAjax(this, {}); 

     // Store plugin object in this element's data 
     element.data('loader', plugin_instance); 
    }); 
}; 

$(document).ready(function(){ 
    $('a#start').click(function(){ 
     var loadingElement = $('.loading.ajax'); 
     loadingElement.loadingAjax(); 
     var plugin_instance = loadingElement.data('loader'); 
     if(plugin_instance.isLoading() === true){ 
      plugin_instance.stopAnimate(); 
     } 
     else{ 
      plugin_instance.startAnimate(); 
     } 
    }); 
}); 

这个环节是非常有益的:http://www.virgentech.com/blog/2009/10/building-object-oriented-jquery-plugin.html

回答

0
$.fn.pluginName = function(){ 
    return this.each(function(){ 
     //Something cool and fancy happens here. 

     //Remember you can have access to the element using the variable 'this'. 
    } 
} 

会让你的插件可供调用$('#element').pluginName()

现在,大约间隔,可以使这样的:

var holder = setInterval(function(){ 
    //The code here repeats every half a second. 
}, 500); 

然后用此清洗:

clearInterval(holder); 

唯一的问题是你必须对范围非常谨慎。制作holder一个全局变量应该可以做到这一点,但我建议你通过阅读this before,借此机会学习一些性感的jutsus。

0

当然,这是可能的,你可以做一些事情,比如使用setInterval并将结果存储在元素的.data中......如果你问这个问题,但你应该多花点时间学习基本知识js和jquery在处理该项目之前。