In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
In this issue, the editor will bring you about how to develop the JQuery plug-in. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.
[preface]
JQuery has been widely used, with its simple API, strong manipulation of DOM, easy expansibility is more and more loved by web developers, I also released a lot of jQuery plug-ins in the community, often people ask some skills, so simply write such an article to all jQuery enthusiasts, can be regarded as throwing a brick to attract jade.
[basic]
A) style
Many people will think that style is a very complicated thing, which requires a calm and calm state of mind and extraordinary aesthetics in order to design a pleasing UI. Apart from picture design, css is actually just those attributes: position,margin,padding,width,height,left,top,float,border,background....
The beauty of UI design depends to a large extent on the designer's grasp of color matching and the coordination of the overall effect. To take a simple example, a simple page, sloppy person:
Test Pagetitle > head > jQuery is a framework! There are more than 30k after compression. Body > html >
A careful person:
Test Pagetitle > body {font-family:' Arial'; font-size:12px;} style > head > jQuery is a framework! There are more than 30k after compression. Body > html >
An attentive person:
Test Pagetitle > body {font-family:'Verdana',' Arial'; font-size:12px;} style > head > jQuery is a framework! There are more than 30k after compression. Body > html >
Let's compare the UI effects of the three:
It is clear at a glance that perhaps many sites lose their attention because of this humble font-family,font-size. Of course, this is only a simple example. Mastering css should start with simplicity, start with the basics, apply it in practice and go deeper and deeper.
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 will say that what is the use of this? in fact, the operation of dom can be easily done through getElementById, getElementsByTagName and other API. This is true. When the idea is determined, thought is the key point, and it is easy to tell whether a piece of code is essence or dross. The reason is still up to you. To give a simple example, a large number of html assemblies.
Passerby A:
Var a = new Array (10); var menu =''; for (var I = 0; I
< a.length; i++) { menu += '' + a[i] + '" >'+ a [I] +';}
Passerby B:
String.prototype.format = function () {var args = arguments; return this.replace (/ {(\ d {1})} / g, function () {return args [arguments [1]];});}; var a = new Array (1, var, 2, 3, 5, 6, 7, 8, 9); var m ='{0}'; for (var I = 0; I)
< a.length; i++) { menu += m.format(a[i]); } 在实现方式明确的情况下,优雅高效的代码显然更具吸引力。 【实践】 jQuery开发或使用,更多的灵感是来自实践,而不是copy||paste(奉行拿来主义的同学可以离开了)。 那么在这里我会用一个简单的例子来阐述jQuery插件开发的流程,能否举一反三就看各位看官了。 【目的】 开发一个插件之前我们需要对自己的目的有一个清醒的认识,有很明确的方向感,那么此次我作为示例插件的目的,就是呈现一个用于UI的Slider - 滑动条,常年从事于或暂时专注于win32开发的同学应该比较了解。 草图 真正动手编码之前我们还需要有一个草图来描述自己插件的"长相"(事件驱动或API封装的可以忽略)。 很多的同学在做UI开发前往往会忙于搜集各种小图片(非精通ps或iconworkshop人士),其实漂亮的图标的确可以美化我们的UI,不过我一般的处理方式是编写易于扩展的css,前期的UI呈现尽量少使用图片,多用线条完成。 ok,言归正卷,那么我的slider设计草图是: 解释下下文将用到的几个词: slider: 此部分是作为拖拽手柄来使用,用户可以通过拖拽此部分来更新completed bar的位置。 completed: 此部分作为bar的内嵌元素,作为特殊效果来显示slider与起始点的距离,亦即与slider的value值关联。 bar: slider的载体,completed的满值。 思路: slider作为手柄提供拖拽功能,作用区域为bar,拖拽过程中completed条必须实时更新(长度),影响区域为slider至bar左端的距离。 【编码】 开发jQuery UI/Effect 插件在很多时候都需要与UI交互,因此在呈现上需要提供Html tree来绘制我们的插件,最终通过js dom来输出,那么在绘制简单的dom结构的时候我会直接用js来完成,不过如果嵌套比较复杂的话,我们还是应该先用html来完成,然后转变成js输出。 html tree: div>Div > div >
Deafultbar-> bar
Jquery-completed-> completed
Jquery-jslider-> slider
In the early UI presentation, we do not use pictures, but try to use lines and colors to complete:
/ *-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 the bar to relative to facilitate the floating of the child node (the child node uses position:absolute to get the inline floating effect).
So 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:
When we draw the UI, we can officially write the jQuery plug-in code, but before we do, we need to have some understanding of the specification of jQuery plug-in development.
1. Use closures:
(function ($) {/ / Code goes here}) (jQuery)
This is a requirement from the official plug-in development specification of jQuery. What are the benefits of using this way of writing?
A) avoid global dependencies.
B) avoid damage by third parties
C) compatible with the jQuery operators'$'and' jQuery'
We know that this code will look like this when parsed:
Var jq = function ($) {/ / Code goes here}; jq (jQuery)
The effect will be clear at a glance.
two。 Expansion
JQuery provides two 'base classes' for users to extend-$. Extend and $. FN. Extend.
Extend is used to extend its own methods, such as $.ajax, $.getJSON, etc., and $.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 minimize the use of $.extend.
3. Selector
JQuery provides a powerful selector that is compatible with various css versions, but it is found that many students do not pay attention to efficiency when using selectors.
A) try to use Id selector. The API used in jQuery selector is based on getElementById or getElementsByTagName, so you can know that the efficiency * * is Id selector, because jQuery will directly call getElementById to obtain dom, while getElementsByTagName is often used to obtain and filter jQuery objects through style selector.
B) the style selector should specify tagName as clearly as possible, if the developer uses the style selector to get dom, and these dom belong to the same type, for example, to get all the div whose className is jquery, then we should use $('div.jquery') instead of $(' .jQuery'). The advantage of writing this is very obvious, when getting dom, jQuery will get div and filter, rather than get all dom re-filter.
C) avoid iterations. Many students prefer to use iterative methods when using jQuery to get dom in a specified context, such as $('.jquery. Child') to get all the nodes under dom where className is jquery and className is child. In fact, it is very expensive to write code like this. JQuery will continue to do deep traversal to get the elements you need, even if you do need it. We should also use methods such as $(selector,context), $('selector1 > selector2'), $(selector1). Children (selector2), $(selctor1). Find (selector2) and so on.
Start coding
The topic is a little too far, ok, after we have a clear understanding of UI, we can use js to output html.
We use jSlider to name the slider plug-in (in order to avoid plug-in conflicts, plug-ins should also be very elaborate naming, I will be vulgar here).
Extend ($.fn, {/ apply a slider UI / jSlider: function (setting) {}})
The standard way in plug-in development is to separate the metadata and open API. For example, the setting parameter here passes values. Sometimes, in order to reduce the amount of code writing, I am used to assigning values directly in the plug-in:
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 practice:
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 role of these API that I have defined:
RenderTo: the carrier and container of jSlider, which can be a jQuery object or a selector.
Enable: whether the jSlider plug-in is available, end-user can be dragged when true, otherwise it is disabled.
InitPosition: the initial value of jSlider, 'max' or' min', that is, the value of slider, 1 or 0.
Size: the parameter of jSlider, including the length of two values barWidth-bar and the length of sliderWidth-slider.
BarCssName: the style name of bar, which makes it easy for end-user to extend the style itself.
CompletedCssName: the style name of the completed.
SliderCssName: the style name of the slider.
SliderHover: the name of the style when slider is focused.
OnChanging: the event triggered when the slider is dragged.
OnChanged: the event triggered at the end of the slider drag.
At this point, we need to cast renderTo into a jQuery object (compatible with the use of selector):
Ps.renderTo = (typeof ps.renderTo = = 'string'? $(ps.renderTo): ps.renderTo)
Then output the html tree to render:
/ *-> html tree:-> sliderbar-> completed bar-> slider percentage, or value value, between 0-1 and 2 > event.
So our jSlider plug-in is basically in shape, providing users with a draggable slider.
[expansion]
Sometimes users are not so easily satisfied, so someone shouted: "I want to set up value myself, why not provide this feature?" .
Then we need to expose a method for the user to set the value of jSlider. The first consideration is that an action object (jSlider) is needed as a method, so at this time I do not want to pass the action object as a parameter, so we develop this method as a plug-in. We name the method setSliderValue and open 2 parameters, v (value) and callback (callback function after setting).
That is: $.fn.setSliderValue (vcallback)
Ok, then the rest is the action object. From the previous design, we know that when dragging slider, it mainly acts on two objects, slider and completedbar, so we add a piece of code at the end of the jSlider plug-in to return the slider object:
Slider.data = {bar: sliderbar, completed: completedbar}; return slider
In this way, when initializing jSlider, we can directly use a variable to get the jSlider object, and then call the setSliderValue method, pseudo code:
Var slider = $.fn.jSlider ({}); slider.setSliderValue (vther 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 sliderboat') } $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 is also called to update the completebar [width] and slider [left] when setting the value of slider. Because the exception handling is done here, you can delete the exception handling code if end-user ensures that the setSliderValue is acting on the jSlider object.
[skin]
According to jSlider's API, we can set the skin for it more conveniently. In order to make jSlider more professional, we need 2 pictures:
The 'bar' used as the completedbar background and the' slider',ok used as the slider background, let's update the style:
/ *-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 let the child node style use the default value of API when setting the style, we only need to set the barCssName when creating the jSlider:
Var blue = $.fn.jSlider ({renderTo:'# slidercontainer', size: {barWidth: 500, sliderWidth: 10}, barCssName: 'bluebar', onChanging: function (percentage, e) {/ / code goes here}})
The rendered UI:
Let's set its value like this:
/ / set percentage with a callback function blue.setSliderValue (.65, function (percentage) {/ / code goes here})
[versatility]
Of course, we can not only use jSlider as a slider, but sometimes it is also a progressbar:
(I won't post the code, just check it in demo; -))
The above is the editor for you to share how to develop the JQuery plug-in, if you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.