People often ask some tips, so simply writing such an article to your jquery enthusiasts is a piece of advice.
Basis
a) style
Many people will think that style is a very complex thing, the need for calm and cool mentality coupled with extraordinary aesthetic to design a pleasing UI, put aside the picture design does not say, in fact, CSS is so some attributes: Position,margin,padding,width,height, Left,top,float,border,background ...
The beauty of the UI design depends to a great extent on the designer's mastery of color matching and the coordination of the overall effect. To give a simple example, a simple page, sloppy person:
Copy Code code as follows:
<title>test page</title>
<body>
jquery is a framework! After compression there are more than 30 K bar.
</body>
A careful person:
Copy Code code as follows:
<title>test page</title>
<style type= "Text/css" >
Body
{
font-family: ' Song body ';
font-size:12px;
}
</style>
<body>
jquery is a framework! After compression there are more than 30 K bar.
</body>
A person who concentrates:
<ptml xmlns= "http://www.w3.org/1999/xhtml" > <pead> <title>test page</title> <style type= " Text/css "> Body {font-family: ' Verdana ', ' XXFarEastFont-Arial '; font-size:12px; } </style> </pead> <body> jquery is a framework! After compression there are more than 30 K bar. </body> </ptml>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]
Let's compare the UI effects of the three:
At a glance, perhaps many of the site lost attention is precisely because of this humble font-family,font-size. Of course, this is just a simple example, master CSS should start from the simple, starting from the basic, in practice and continue to deepen.
b) Script
We also need to have a deep understanding of JavaScript, Dom, XHR, Regex, call-apply, prototype and so on should have a certain understanding.
Some people would say that's what it's all about. The operation of the DOM is actually done through getElementById, getElementsByTagName and other APIs, which is true, when the idea is fixed, the thought is the key, A piece of code is the essence or the dross can easily be differentiated, the reason is still depends on yourself, for a simple example, a large number of HTML assembly, passerby a:
Copy Code code as follows:
var a = new Array (10);
var menu = ';
for (var i = 0; i < a.length; i++) {
menu = ' <li class= ' style_ ' + a[i] + ' > ' + a[i] + ' </li> ';
}
Passerby B:
Copy Code code 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 = ' <li class= ' style_{0} ' >{0}</li> ';
for (var i = 0; i < a.length; i++) {
Menu + + M.format (A[i]);
}
Elegant and efficient code is clearly more appealing in a way that is clearly implemented.
"Practice"
jquery development or use, more inspiration is from practice, not copy| | Paste (the copycat students can leave).
So here I will use a simple example to illustrate the jquery plug-in development process, whether extrapolate to see you see Officer.
"Purpose"
To develop a plug-in before we need to have a clear understanding of their own purposes, there is a sense of direction, so this time I as a sample plug-in for the purpose of rendering a UI for the slider-slider, year-round engaged in or temporarily focused on the development of Win32 students should be more understanding.
Sketch
We also need to have a sketch to describe the "look" of the plugin (event-driven or API encapsulation can be ignored) before really coding.
Many students are often busy collecting small pictures (not proficient in PS or IconWorkshop) before doing UI development. In fact, beautiful icons can indeed beautify our UI, but my general approach is to write easy to expand the CSS, the early UI rendering as little as possible to use the picture, more lines to complete.
OK, the word is roll, then my slider design sketch is:
Explain several words that will be used in the following paragraphs:
Slider: This section is used as a drag-and-drop handle, which allows the user to update the location of completed bar by dragging this section.
Completed: This section acts as an inline element of bar, as a special effect to show the distance from the slider to the starting point, which is associated with the value value of slider.
Bar:slider carrier, full value of completed.
idea:
Slider as a handle to provide drag-and-drop function, the action area is bar, the completed bar must be updated in real time (length), the impact area is slider to bar the left side of the distance.
"Encoding"
The development of jquery Ui/effect Plug-ins in many cases need to interact with the UI, so the rendering of the need to provide HTML tree to draw our plug-ins, and ultimately through the JS Dom output, then in the drawing of a simple DOM structure I will be directly using JS to complete, However, if the nesting is more complex, we should first use HTML to complete, and then converted to JS output.
HTML tree:
Copy Code code as follows:
<div class= "Defaultbar" >
<div class= "jquery-completed" > </div>
<div class= "Jquery-jslider" > </div>
</div>
Deafultbar-> Bar
jquery-completed-> Completed
Jquery-jslider-> Slider
Early UI rendering we do not use the picture, as far as possible with lines, colors to complete:
Css
Copy Code code 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 property of bar to relative to facilitate the floating of child nodes (child nodes use Position:absolute for inline floating effects).
So we can look at the UI effects of this CSS and HTML tree:
OK, with the required elements-slider, completed, bar.
Some specifications:
We can formally write jquery plug-in code after we have drawn the UI, but before we do we need to know some of the standardization of JQuery plug-in development.
1. Use closures:
Copy Code code as follows:
(function ($) {
Code goes here
}) (JQuery);
This is from the jquery official plug-in development specification requirements, what is the benefit of using this writing method?
(a) Avoid global dependencies.
(b) Avoidance of third party damage.
c) compatible jquery operator ' $ ' and ' jquery '
We know that this code will be parsed to form the following code:
Copy Code code as follows:
var JQ = function ($) {
Code goes here
};
JQ (JQuery);
This effect is at a glance.
2. Extended
jquery provides 2 user-extended ' base classes '-$.extend and $.fn.extend.
$.extend is used to extend its own methods, such as $.ajax, $.getjson, and $.fn.extend is used to extend the jquery class, including methods and operations on jquery objects. To keep the integrity of jquery, I tend to use $.fn.extend for plug-in development with minimal use of $.extend.
3. Selector
jquery provides a powerful and compatible selector for a variety of CSS versions, but finds that many students do not focus on efficiency when using selectors.
A as far as possible using the ID selector, the jquery selector uses the API is based on getElementById or getelementsbytagname, therefore can know the most efficient is the ID selector, Because jquery invokes getElementById directly to get the DOM, the getElementsByTagName is often used to get the jquery object through the style selector and then filtered.
b The style selector should specify TagName as clearly as possible, and if the developer uses the style selector to get the DOM, and the DOM belongs to the same type, for example, to get all the div classname for jquery, then we should use the notation $ (' div.jquery ') Instead of $ ('. jquery '), the benefits of this writing are obvious, and when you get the DOM, jquery takes the div and then filters it instead of getting all the DOM filters.
C to avoid iterations, many students prefer to use the iterative approach when using jquery to get the DOM in the specified context, such as $ ('. jquery. Child '), to get all the classname for children under the DOM classname jquery. In fact, the cost of writing code is very large, jquery will continue to carry out deep traversal to get the required elements, even if it is really necessary, we should use such as $ (Selector,context), $ (' Selector1>selector2 '), $ ( Selector1). Children (Selector2), $ (Selctor1). Find (Selector2) and the like.
Start Encoding
The topic is a bit far, OK, after 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 be very elegant, here I am a custom).
Copy Code code as follows:
$.extend ($.fn, {
<summary>
Apply a slider UI
</summary>
Jslider:function (setting) {
}
});
The way to compare the standard in plug-in development is to separate the metadata and open the API, such as the setting parameter pass in the value, sometimes in order to reduce the amount of code written, I am accustomed to directly in the plug-in assignment:
Copy Code code 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);
Normative approach:
Copy Code code 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, below is a description of the role of these APIs that I have defined:
Renderto:jslider carrier, container, can be a jquery object, can also be a selector.
Enable:jslider plug-in is available, true when end-user can be dragged, otherwise prohibited.
The initial value of the Initposition:jslider, ' Max ' or ' min ', that is, the value of slider, 1 or 0.
Size:jslider parameters, including the length of the 2-value barwidth-bar, the length of the Sliderwidth-slider.
The Barcssname:bar style name makes it easy for end-user to extend the style itself.
Completedcssname:completed the name of the style.
Slidercssname:slider the name of the style.
Sliderhover:slider the style name when focusing.
The event that is triggered when the onchanging:slider is dragged.
Onchanged:slider the event that is triggered at the end of the drag.
At this point we need to cast the Renderto into a jquery object (compatible with selector):
Ps.renderto = (typeof Ps.renderto = = ' string '?)
$ (Ps.renderto): Ps.renderto);
The HTML tree is then exported to render:
/*---------->
HTML tree:
Copy Code code as follows:
<div>---->sliderbar
<div> </div>----> Completed bar
<div> </div>----> Slider
</div>
<-----------* *
var Sliderbar = $ (' <div><div> </div><div> </div></div> ')
. 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);
This allows us to render HTML directly on the UI and render with custom CSS, using Sliderbar, Completedbar, and slider to cache the three objects we need.
OK, after rendering the UI we need to provide a way to achieve slider drag, before we need to implement a method, that is, Completedbar real-time update, that is, when dragging slider Completedbar always fill the left area:
Copy Code code as follows:
var bw = Sliderbar.width (), SW = Slider.width ();
Make sure that the slider is 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 is used to store the length of the Sliderbar and slider, and there is no direct use of the Ps.size value to prevent the border-width in the style from causing damage to the width.
Define a private member limited to store the maximum and minimum values of slider[left] and use the eval (' ps.limited. ' + ps.initposition) directly later to avoid the switch operation.
You also need to define a global function to locate the Completedbar padding length and the slider left distance, which I named $sliderprocess.
Then the rest of our work is the slider drag and drop function, then I will use the previous release of a jquery drag and drop plug-ins, and do a proper amount of custom:
Copy Code code as follows:
//drag and drop
var slide = {
Drag:function (e) {
var d = E.D Ata
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 (' left '))/slider.css X, 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);
});
}
So when the JSlider enable property is True, end-user bind the MouseMove event when the mouse is pressed, and remove when the mouse is bouncing, we only need to synchronize the left property of the slider and the width of the completedbar. At the same time, bind the Onchanging method in drag, bind the OnChanged method in the drop, and push the two methods to the same,1> percent, that is, value, between 0~1,2>event.
So far our JSlider plug-in on the basic molding, to provide users with a drag-and-drop slider.
"Extended"
Sometimes the user is not so easy to meet, so someone shouted: "I want to set the value of their own, why do not provide this function?" ”。
Then we need to expose a method for the user, to set the value of JSlider, first of all consider as a method requires a jslider, then I do not want to pass the object as a parameter, then we still use this method as a plug-in to develop, We name the method Setslidervalue, open 2 parameters, V (value), and callback (set the callback function after completion).
namely: $.fn.setslidervalue (V,callback);
OK, then the rest is the role of the object, by the previous design that the slider drag when the main role in 2 objects, slider and Completedbar, then we add a 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 initialize the JSlider directly with a variable to get the JSlider object, and then call the Setslidervalue method, pseudo code:
Copy Code code 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 ' object ', not a slider! ');
}
$sliderProcess (S, s.data.completed, V * s.data.bar.width ());
if (typeof callback!= ' undefined ') {callback (v);}
}
catch (e) {
alert (e.message);
}
The global function $sliderProcess also called to update the completedbar[width] and Slider[left when setting slider value values. Because of the exception handling here, end-user can remove this exception handling code if it ensures that Setslidervalue is acting on the JSlider object.
Skin
According to the JSlider API we can more easily set the skin for it, in order to make jslider more professional, we need 2 photos:
The ' bar ' used as a completedbar background and the ' slider ' used as a slider background, OK, we update the following style:
Blueskin
Copy Code code 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;
}
Because I still have the child node style use the default value of the API when I set the style, we just need to set the barcssname when creating JSlider:
Copy Code code as follows:
var blue = $.fn.jslider ({
Renderto: ' #slidercontainer ',
Size: {barwidth:500, sliderwidth:10},
Barcssname: ' Bluebar ',
Onchanging:function (percentage, E) {
Code goes here
}
});
Rendered UI:
Let's set its value like this:
Copy Code code as follows:
Set percentage with a callback function
Blue.setslidervalue (0.65, function (percentage) {
Code goes here
});
"Versatility"
Of course, not only can we use JSlider as slider, sometimes it's also a ProgressBar:
(Code I will not post, directly in the demo view;-))
Summary
This is the end of the whole, the simple introduction of a jquery plug-in development process, as well as the development should pay attention to the details, then in the next article I will show you how to create a general-purpose automatic completion plug-in.