简体   繁体   English

编写和编译一个简单的jQuery插件

[英]Writing and compiling a simple jQuery plugin

I am trying to compile a basic jQuery plugin which shows a div upon provided options when invoking: 我正在尝试编译一个基本的jQuery插件,该插件在调用时在提供的选项上显示div:

  • select if a checkbox should be checked after X milliseconds or after X px on scroll, 选择是否应在X毫秒后或滚动X px后选中一个复选框,
  • if one of those two options are selected, set a delay value or scroll distance in px 如果选择了这两个选项之一,则以px为单位设置延迟值或滚动距离
  • otherwise do nothing 否则什么都不做

Example of desired options invoke: 所需选项的示例调用:

    $(document).ready( function() {
        $('#testInput').testing({
            myMethod      : delay,
            myValue       : 2000
        });
});

My current progress here: JSFiddle (it's not much as currently I'm still at a beginning of the learning curve) 我目前在这里取得的进展: JSFiddle (与目前的学习曲线尚不多)

After some fiddling i managed to get this working (kinda). 经过一番摆弄之后,我设法使它正常工作。 Plugin seems to be working fine. 插件似乎运行良好。 Except there is some bug with the scroll function which i have to sort it out additionaly - it loops and changes checkbox states indefinitely instead just once. 除非滚动功能存在一些错误,否则我必须对它进行额外的整理-它循环并无限期地更改复选框状态,而不仅仅是一次。

Here is a working fiddle 这是一个工作的小提琴

And modified code: 并修改代码:

(function($) {

$.fn.testing = function( options ) {

    // Settings
    var settings = $.extend({
        delay           : null,
        delayTime       : null,
        scrolling       : null,
        scrollDist      : null
    }, options);

    return this.each( function() {
        var self = this;

        // Timeout
        setTimeout(function (){
           $(self).prop('checked', settings.delay);
        }, settings.delayTime);

        // Scroll
       if ($(window).scrollTop() > settings.scrollDist) {
          $(this).prop('checked', settings.scrolling);
       };

    });

}

}(jQuery));

// Plugin invoke
$(window).on("load resize scroll",function(){
    $('#testInput').testing({
        delay             : false,
        delayTime         : null,
        scrolling         : true,
        scrollDist        : 20,
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM