Home > Web Front-end > JS Tutorial > body text

jQuery plug-in development is actually very simple_jquery

WBOY
Release: 2016-05-16 18:50:24
Original
935 people have browsed it

People often ask about some tips, so I decided to write this article for all jQuery enthusiasts, as a way to attract others.
【Basics】
a) Style
Many people think that style is a very complicated thing. It requires a calm mind and extraordinary aesthetics to design a pleasing UI. Leaving aside the image design, in fact, CSS only has these attributes: position, margin, padding, width, height, left, top, float, border, background...

The beauty of the UI design lies in To a large extent, it depends on the designer's grasp of color matching and coordination of the overall effect. Take a simple example, a simple page, sloppy people:

Copy the code The code is as follows:



Test Page


jQuery is a framework! After compression, it is more than 30k.




Careful people:

Copy the code The code is as follows:


< head>
Test Page



jQuery is a framework! After compression, it is more than 30k.



A dedicated person:


[Ctrl A Select all Note: If you need to introduce external Js, you need to refresh it to execute ]

Let’s compare the three UI effect:



Clear at a glance, perhaps many sites have lost attention precisely because of this inconspicuous font-family, font-size. Of course, this is just a simple example. To master CSS, you should start simple, start with the basics, apply it in practice and continue to deepen it.
b) Script
We also need to have a deep understanding of javascript, and should have a certain understanding of dom, xhr, Regex, call-apply, prototype, etc.

Some people will say what is the use of these? In fact, the operation of DOM can be easily completed through getElementById, getElementsByTagName and other APIs. This is true. After the idea is determined, the thinking is the focus. , it is easy to distinguish whether a piece of code is the essence or the dross. The reason still depends on you. To give a simple example, a large number of html assembly, passerby A:

Copy code The code is as follows:

var a = new Array(10);
var menu = '';
for ( var i = 0; i < a.length; i ) {
menu = '
  • ' a[i] '
  • ';
    }


    Passerby B:

    Copy the code The code is as follows :

    String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(d{1})}/g, function( ) {
    return args[arguments[1]];
    });
    };
    var a = new Array(1,2,3,4,5,6,7,8, 9,0);
    var m = '
  • {0}
  • ';
    for (var i = 0; i < a. length; i ) {
    menu = m.format(a[i]);
    }

    When the implementation method is clear, elegant and efficient code is obviously more attractive.
    [Practice]
    JQuery development or use, more inspiration comes from practice, rather than copy||paste (students who pursue the principle of borrowing can leave).
    So here I will use a simple example to explain the process of jQuery plug-in development. It is up to you whether you can draw inferences from one example.

    [Purpose]

    Before developing a plug-in, we need to have a clear understanding of our purpose and a clear sense of direction. So this time I will serve as an example The purpose of the plug-in is to present a Slider for UI. Students who have been engaged in or temporarily focused on win32 development should be familiar with it.

    Sketch


    Before we actually start coding, we also need a sketch to describe the "look" of our plug-in (event-driven or API encapsulated ones can be ignored).
    Many students are often busy collecting various small pictures before doing UI development (those who are not proficient in PS or iconworkshop). In fact, beautiful icons can indeed beautify our UI, but my general approach is to write easy-to-expand css, the early UI presentation uses as few pictures as possible and uses more lines.
    ok, let’s get back to the point, then my slider design sketch is:


    Explain the words that will be used below:
    slider: This part is used as a drag handle To use, the user can update the position of the completed bar by dragging this part.
    completed: This part is used as an embedded element of the bar and is used as a special effect to display the distance between the slider and the starting point, that is, it is associated with the value of the slider.
    bar: The carrier of the slider, the full value of completed.

    Idea:
    Slider serves as a handle to provide dragging function. The affected area is bar. During the dragging process, the completed bar must be updated (length) in real time. The affected area is from slider to the left end of bar. distance.

    [Coding]

    Developing jQuery UI/Effect plug-ins requires interacting with the UI many times, so we need to provide an Html tree to draw our plug-in during presentation. Finally, the output is through js dom, so when drawing a simple dom structure, I will use js directly to complete it. However, if the nesting is more complicated, we should still use html to complete it first, and then convert it to js output.

    html tree:

    Copy code The code is as follows:





    deafultbar -> bar
    jquery-completed -> completed
    jquery-jslider -> slider

    Preliminary UI presentation on us Do not use pictures, try to use lines and colors to complete:
    Css
    Copy code The code is as follows:

    /**//*----default skin----*/
    .defaultbar
    {}{
    margin-top: 10px;
    height: 5px;
    background-color: #FFFFE0;
    border: 1px solid #A9C9E2;
    position: relative;
    }
    .defaultbar .jquery-completed
    {}{
    height: 3px;
    background-color: # 7d9edb;
    top: 1px;
    left:1px;
    position: absolute;
    }
    .defaultbar .jquery-jslider
    {}{
    height: 15px;
    background-color: #E6E6FA;
    border: 1px solid #A5B6C8;
    top: -6px;
    display: block;
    cursor: pointer;
    position: absolute;
    }

    Set the position attribute of bar to relative to facilitate the floating of child nodes (child nodes use position:absolute to obtain inline floating effects).
    Then we can take a look at the UI effect produced by this css and html tree:

    ok, with the required elements - slider, completed, bar.
    Some specifications:

    After we draw the UI, we can formally write the jQuery plug-in code, but before that we need to have some understanding of some of the norms of jQuery plug-in development.
    1. Use closures:

    Copy code The code is as follows:

    (function($) {
    // Code goes here
    })(jQuery);

    This is the official plug-in development specification requirement from jQuery, use What are the benefits of writing this way?

    a) Avoid global dependencies.

    b) Avoid third party damage.
    c) Compatible with jQuery operator '$' and 'jQuery '

    We know that this code will look like the following code when parsed:

    Copy code The code is as follows:

    var jq = function($) {
    // Code goes here
    };
    jq(jQuery);

    The effect is clear at a glance.

    2. Extensions
    jQuery provides 2 'base classes' for users to extend - $.extend and $.fn.extend.

    $. extend is used to extend its own methods, such as $.ajax, $.getJSON, etc. $.fn.extend is used to extend the jQuery class, including methods and operations on jQuery objects. In order to maintain the integrity of jQuery, I tend to use $.fn.extend for plug-in development and use $.extend as little as possible.
    3. Selector
    jQuery provides powerful functions. It is also compatible with multiple CSS versions of selectors, but it is found that many students do not pay attention to efficiency when using selectors.
    a) Try to use the Id selector. The API used by jQuery's selector is based on getElementById or getElementsByTagName. Therefore, you can know that the most efficient one is the Id selector, because jQuery will directly call getElementById to get the dom, and select it through the style. When the browser obtains jQuery objects, it often uses getElementsByTagName to obtain and then filter.
    b) The style selector should try to specify the tagName clearly. If the developer uses the style selector to obtain DOM, and these DOM are of the same type, for example, to obtain all divs whose className is jquery, then the writing method we should use is $( 'div.jquery') instead of $('.jquery'). The benefit of writing this way is very obvious. When getting the dom, jQuery will get the div and then filter it, instead of getting all the dom and then filtering.
    c) Avoid iteration. Many students like to use iteration when using jQuery to obtain the DOM in the specified context, such as $('.jquery .child') to obtain all nodes with className as child under the DOM with className of jquery. , in fact, the cost of writing code like this is very high. jQuery will continue to perform deep traversal to obtain the required elements. Even if it is really needed, we should use methods such as $(selector,context), $('selector1>selector2') , $(selector1).children(selector2), $(selctor1).find(selector2) and so on.

    Start coding

    The topic is a bit far-fetched, ok, after we have a clear understanding of the UI, we can use js to output html.
    We use jSlider to name this slider plug-in (in order to avoid plug-in conflicts, plug-in naming should also be very particular, I will be simple here).
    Copy code The code is as follows:

    $.extend($.fn, {
    ///
    /// apply a slider UI
    ///

    jSlider: function(setting) {
    }
    });

    The standard way in plug-in development is to separate the metadata and open the API. For example, the setting parameter here is passed in a value. Sometimes in order to reduce the amount of code writing, I am used to assigning values ​​directly within the plug-in. :

    Copy code The code is as follows:

    var ps = $.extend({
    renderTo: $(document.body),
    enable: true,
    initPosition: 'max',
    size: { barWidth: 200, sliderWidth: 5 },
    barCssName: 'defaultbar ',
    completedCssName: 'jquery-completed',
    sliderCssName: 'jquery-jslider',
    sliderHover: 'jquery-jslider-hover',
    onChanging: function() { },
    onChanged: function() { }
    }, setting);

    Standard approach:

    Copy code The code is as follows:

    $.fn.jSlider.default = {
    renderTo: $(document.body),
    enable: true,
    initPosition: 'max',
    size: { barWidth: 200, sliderWidth: 5 },
    barCssName: 'defaultbar',
    completedCssName: 'jquery-completed',
    sliderCssName: 'jquery- jslider',
    sliderHover: 'jquery-jslider-hover',
    onChanging: function() { },
    onChanged: function() { }
    };
    $.extend({ },$.fn.jSlider.default,setting);

    ok, the following describes the functions of these APIs I defined:
    renderTo: jSlider’s carrier and container, which can be a jQuery object or a selector.
    enable: Whether the jSlider plug-in is available. If true, end-user can drag and drop, otherwise it is prohibited.
    initPosition: The initial value of jSlider, 'max' or 'min', that is, the value of the slider, 1 or 0.
    size: jSlider parameters, including 2 values ​​barWidth - the length of the bar, sliderWidth - the length of the slider.
    barCssName: The style name of bar, which makes it easy for end-user to extend the style by himself.
    completedCssName: Completed style name.
    sliderCssName: The style name of the slider.
    sliderHover: The style name when the slider is focused.
    onChanging: Event triggered when the slider is dragged.
    onChanged: Event triggered when the slider drag ends.

    At this point we need to force convert renderTo into a jQuery object (compatible with using selector):

    ps.renderTo = (typeof ps.renderTo == 'string' ?
    $ (ps.renderTo) : ps.renderTo);
    Then output the html tree to render:

    /* ---------->
    html tree:
    Copy code The code is as follows:

    ---->sliderbar
    ----> completed bar
    ----> slider

    <- ----------*/
    var sliderbar = $('
    ')
    .attr('class', ps.barCssName)
    .css('width', ps.size.barWidth)
    .appendTo(ps.renderTo);
    var completedbar = sliderbar.find ('div:eq(0)')
    .attr('class', ps.completedCssName);
    var slider = sliderbar.find('div:eq(1)')
    .attr( 'class', ps.sliderCssName)
    .css('width', ps.size.sliderWidth);

    In this way, we present the Html directly on the UI and use customized css For rendering, use sliderbar, completedbar, and slider to cache the three objects we need.

    ok, after the UI is presented, we need to provide a method to realize the dragging of the slider. Before that, we also need to implement a method, which is the real-time update of the completedbar, that is, when the slider is dragged, the completedbar Always fill the left area:

    Copy code The code is as follows:

    var bw = sliderbar.width(), sw = slider.width();
    //make sure that the slider was displayed in the bar(make a limited)
    ps.limited = { min: 0, max: bw - sw };
    if (typeof window.$sliderProcess == 'undefined') {
    window.$sliderProcess = new Function('obj1', 'obj2', 'left',
    'obj1.css ('left',left);obj2.css('width',left);');
    }
    $sliderProcess(slider, completedbar, eval('ps.limited.' ps.initPosition));

    bw, sw are used to store the length of sliderbar and slider. The value in ps.size is not used directly here to prevent the border-width in the style from damaging the width.

    Define a private member limited to store the maximum and minimum values ​​of slider[left], and directly use eval('ps.limited.' ps.initPosition) to obtain them later, thereby avoiding switch operations.
    At the same time, a global Function needs to be defined to locate the filling length of the completed bar and the left distance of the slider. I named it $sliderProcess.
    Then the next thing we have to do is to drag and drop the slider, so here I will use a jQuery drag and drop plug-in that was released before, and make appropriate customizations:

    Copy code The code is as follows:

    //drag and drop
    var slide = {
    drag : function(e) {
    var d = e.data;
    var l = Math.min(Math.max(e.pageX - d.pageX d.left, ps.limited.min), ps. limited.max);
    $sliderProcess(slider, completedbar, l);
    //push two parameters: 1st:percentage, 2nd: event
    ps.onChanging(l / ps.limited.max, e );
    },
    drop: function(e) {
    slider.removeClass(ps.sliderHover);
    //push two parameters: 1st:percentage, 2nd: event
    ps. onChanged(parseInt(slider.css('left')) / sw - ps.limited.max, e);
    $().unbind('mousemove', slide.drag).unbind('mouseup', slide .drop);
    }
    };
    if (ps.enable) {
    //bind events
    slider.bind('mousedown', function(e) {
    var d = {
    left: parseInt(slider.css('left')),
    pageX: e.pageX
    };
    $(this).addClass(ps.sliderHover);
    $().bind('mousemove', d, slide.drag).bind('mouseup', d, slide.drop);
    });
    }

    In this way, when the jSlider enable attribute is true, the mousemove event is bound when the end-user presses the mouse, and is removed when the mouse pops up. We only need to synchronously update the left attribute of the slider and the width of the completedbar. At the same time Bind the onChanging method in drag and the onChanged method in drop. The parameters pushed to these two methods are the same, 1>percent, that is, value, ranging from 0~1, 2>event.

    So now our jSlider plug-in has basically taken shape, providing users with a draggable slider.

    [Extension]
    Sometimes users are not so easily satisfied, so someone shouted: "I want to set the value myself, why not provide this function?".

    Then we need to expose a method to the user to set the value of jSlider. The first thing to consider is that the method requires an action object (jSlider), so at this time I don’t want to use the action object as a parameter. Pass in, then we will develop this method as a plug-in. We name the method setSliderValue and open two parameters, v (value) and callback (callback function after setting is completed).

    That is: $.fn.setSliderValue(v,callback);
    ok, then the rest is the action object. From the previous design, we can know that when the slider is dragged, it mainly acts on 2 objects. , slider and completedbar, then we add a piece of code at the end of the jSlider plug-in to return the slider object:

    Copy code Code As follows:

    slider.data = { bar: sliderbar, completed: completedbar };
    return slider;

    In this way we can directly initialize jSlider Use a variable to get the jSlider object, and then call the setSliderValue method. Pseudo code:

    Copy code The code is as follows:

    var slider = $.fn.jSlider({});
    slider.setSliderValue(v,function(){});
    setSliderValue code:

    try {
    //validate
    if (typeof v == 'undefined' || v < 0 || v > 1) {
    throw new Error(''v' must be a Float variable between 0 and 1.');
    }
    var s = this;
    //validate
    if (typeof s == 'undefined' ||
    typeof s.data == 'undefined ' ||
    typeof s.data.bar == 'undefined') {
    throw new Error('You bound the method to an object that is not a slider!');
    }
    $sliderProcess(s, s.data.completed, v * s.data.bar.width());
    if (typeof callback != 'undefined') { callback(v); }
    }
    catch (e) {
    alert(e.message);
    }

    Here the global Function $sliderProcess is also called to perform completedbar[width] and Update of slider[left]. Since exception handling is performed here, if the end-user can delete this exception handling code when ensuring that setSliderValue is applied to the jSlider object.
    【Skin】
    According to jSlider’s API we can more conveniently set a skin for it. In order to make jSlider more professional, we need 2 pictures:

    to be used as the completedbar background 'bar' and 'slider' used as slider background, ok, let's update the style:

    BlueSkin
    Copy code The code is as follows:

    /**//*----blue skin----*/
    .bluebar
    {}{
    margin-top: 10px;
    height: 4px;
    background:#F7F7F7;
    border:solid 1px #3e3e3e;
    position: relative;
    }
    .bluebar .jquery-completed
    {}{
    height : 4px;
    background:url(../images/slider/blue/bar.gif) left center no-repeat;
    top: 0;
    left:0;
    position: absolute;
    }
    .bluebar .jquery-jslider
    {}{
    height: 17px;
    background:url(../images/slider/blue/slider.gif) center 0 no- repeat;
    top: -4px;
    display: block;
    cursor: pointer;
    position: absolute;
    }
    .bluebar .jquery-jslider-hover
    { }{
    background-position:center -17px;
    }

    Since I still let the child node style use the default value of the API when setting the style, when creating the jSlider we Just set barCssName:

    Copy code The code is as follows:

    var blue = $.fn.jSlider({
    renderTo: '#slidercontainer',
    size: { barWidth: 500, sliderWidth: 10 },
    barCssName: 'bluebar',
    onChanging: function(percentage , e) {
    // code goes here
    }
    });

    The UI presented:


    We set its value like this:

    Copy code The code is as follows:

    //set percentage with a callback function
    blue.setSliderValue(0.65, function(percentage) {
    // code goes here
    });

    【Universality】
    Of course, we can not only use jSlider as a slider, sometimes it is also a progressbar:

    (I won’t post the code, check it directly in the demo ;-) )
    [Summary]
    This ends here. It briefly introduces the development process of a jQuery plug-in, and Details that should be paid attention to during development, then in the next article I will introduce to you how to create a universal auto-complete plug-in.
    Related labels:
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template