Home Web Front-end JS Tutorial jQuery plug-in development is actually very simple_jquery

jQuery plug-in development is actually very simple_jquery

May 16, 2016 pm 06:50 PM
jquery Plug-in development

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
    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.
    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

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

    Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

    How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

    How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

    How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

    How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

    In-depth analysis: jQuery's advantages and disadvantages In-depth analysis: jQuery's advantages and disadvantages Feb 27, 2024 pm 05:18 PM

    jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

    jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

    Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

    Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

    Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

    How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

    How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

    Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

    jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

    See all articles