Front-end Programming Improvement Tour (II) jquery implementation of common effects----site

Source: Internet
Author: User

The best programming language is logic, and the implementation of the front-end interactive effects can be implemented with jquery. Effects can be swirling. The intrinsic logic is essentially the same. This article focuses on the logic behind jquery for common effects.

1. Get the collection of elements through the class name

Let's start with a method that JS native code does not support. Gets the collection of elements through the class.

Document.getelementsbyclassname=function (classname) {  var retnode = [];  var myclass = new RegExp (' \\b ' +classname+ ' \\b ');//Match class name  var elem = this.getelementsbytagname (' * ');//Get all elements for  (var j = 0; J < Elem.length; J + +)   {   var classes = elem[j].classname;   if (Myclass.test (classes)) {    Retnode.push (elem[j]);   }  }  return retnode;} By traversing the entire document element class name. Returns an array of all specified class names

Logical thinking:

By constructing a regular form of a class name. Select all tags and match them with the full label class Name property, returning a class an array group to achieve the target of the collection of elements through the class name.

The same time that this approach is implemented, it also gives the convenience of selecting elements of a particular ordinal without using jquery.

2. Construction of two-level linkage menu

$ ("#select1"). Change (function () {//detects the change event of a first-level menu  var id = $ ("#select1"). Val ();  if (id = = 1) {//by ID infer level two menu   $.get (' index.php ', NULL, function (data) {//get method value    $ ("span"). empty ();//Empty label    $ ("span"). Append ("<select><option> jinan </opton><option> Qingdao </opton><option> Linyi </opton></select>);//fill in the corresponding level two menu   });   } else{   $.get (' index.php ', NULL, function (data) {//get means value    $ ("span"). empty ();//Empty label    $ ("span"). Append ("<select><option> Zhengzhou </opton><option> Anyang </opton><option> Luoyang </opton>< /select> ");//fill in the corresponding level two menu    });}  );

Logical thinking:

According to the need to set the linkage menu element value is changed, through the Ajax method to pass the null value to its own page. Append the corresponding element, here is the level two menu.

There are two methods of jquery: The change method and the empty method.

The change method is triggered to run when the selected tag value changes.

The empty method is to empty the HTML contents of the label.

3. Link style and display of linked content hidden

$ (function () {  $ ("Li"). each (function (index) {///Traverse User Control Area  $ (this). MouseOver (function () {//Get the current user to select the zone   ID = SetTimeout (function () {///Use time event function to achieve a better user experience with ease effect   $ ("Li.tab"). Removeclass (' tab ');//Remove Default option button style   $ ( This). addclass ("tab"); Add Style $ ("div.show") to the current option button   . Removeclass (' show ');//Remove the default display area style   $ ("#tab1 div:eq (" +index+ "). AddClass (' show ');//Add style},300 according to the selected index index)  . Mouseout (function () {  cleartimeout (ID);//removal of time event at the same time when the user mouse is removed   });});  /link the corresponding content hidden and displayed

Logical thinking:

This is the first use of $ () in the writing function, here specifically describes the jquery constructor application scope. By traversing each navigation link. When the mouse moves over the corresponding element. First Remove all default option styles, plus the default check style for suspended elements.

and remove the current display style, set the default option to the corresponding content style to display state.

The highlight here is the use of an easing effect that shows the default style. The user experience is more careful.

4. Implementation of "show many other (more)" Features

$ (function () {var $hideObj = $ (' ul li:gt (5): Not (: last) ');//Select the LI element with index greater than or equal to 5. Remove the last one, hide the $hideobj.hide (); $ ('. ShowMore span '). Click (function () {if (! $hideObj. Is (": visible")) {//infer if the IS method $ Hideobj.show (); $ ('. ShowMore span '). CSS ("Background", "url (./images/up.bmp) no-repeat 0-10");//Toggle Status Change Picture}else{$ Hideobj.hide (); $ ('. ShowMore span '). CSS ("Background", "url (./images/down.bmp) no-repeat 0 0");//Toggle status Change Picture}); /select part to hide, then partially infer whether to display, show or hide

Logical thinking:

This first uses the selector to remove the last element of the Li element that is all greater than 5 selected. By clicking on the event, the user infers whether to show or hide, and to change the clicked icon.

Highlights in the control of the selector to the advantage, with jquery the most important to use the ripe selector. This allows the DOM nodes to be operated at High speed and efficiency . It's easy to understand why CSS3 is the first to change the selector, simplifying the process, regularization, and semantic CSS selectors, making it easier for front-end project architects to read and write code.

5. Text field "remaining words"

$ (document). Ready (function () {  Vartarea = $ ("#init");//  Tarea.focus (function () {   $ ("#numtj"). FadeIn (  }). Blur (function () {   $ ("#numtj"). FadeOut ("slow");  }) The text field gets focus and loses focus the remaining number of words is displayed or disappears, using the fade-in fade-out  $ ("#init"). KeyUp (function () {   vartext=$ ("#init"). Val ();   Varcounter=text.length;   $ ("#numtj var"). Text (110-counter);  }); /press the keyboard to change the remaining words in real time});

Logical thinking:

Logic is easy. Gets the focus remaining word count display. Lost focus the remaining number of words disappears. The keyboard calculates the number of words left.

The highlight here is the use of the Fadein and fadeout methods to achieve a more natural and gradual fade-in. Experience better. The focus and Blur events are also events that often need to be handled for elements with input content. KeyUp events are related to user input, real-time interaction.

6. Move the mouse to the image to enlarge

Varshowimage =function () {  xoffset=;  yoffset=;  $ ("#imglist"). FIND ("img"). Hover (function (e) {//Add event to Picture object and trigger function   $ (" "). AppendTo (" body ");//Add Picture object on Body   $ (" #imgshow ")    . CSS (" Top ", (E.pagey-xoffset) +" px ")//Position body displays the y-coordinate of the picture The mouse position is set to offset manually    . CSS ("Left", (E.pagex + yoffset) + "px")//positioning body Display diagram    . FadeIn ("fast");   },function () {    $ (" #imgshow "). Remove ();   });   $ ("#imglist"). FIND ("img"). MouseMove (function (e) {    $ ("#imgshow"). CSS ("Top", (E.pagey-xoffset) + "px")    . CSS ("Left", (E.pagex + yoffset) + "px");}   );  

Logical thinking:

The logic of this code is very universal, E for mouse events, mouse properties Pagex and Pagey represent the coordinates of the mouse position. The overall idea is to trigger a hover event via the mouse. Displays or removes a picture that has an offset from the mouse position and moves the magnified position in real time by setting the MouseMove event.

looking at the above examples we will find that events and selectors are the core of the overall interaction effect. So it's necessary to be proficient and proficient again.

7. Picture Carousel

Vart = 0; Varn = 0; varcount;//global variable communication function and the Click event within the variable $ (document). Ready (function () {count=$ ("#bannerList a"). length;//gets the total number of user control a tags $ ("# Bannerlist A:not (: First-child) "). Hide ();///except the first element is hidden $ (" #banner li "). Click (function () {///To add a list of the pictures to the event Vari =$ (this ). Text ()-1;//Gets the value within the LI element, which is a.   The value of 4 n =i;//i is assigned to n if (I >= count) {//inferred if the total number of the A label is greater than return; } var$a = $ ("#bannerLista"). Filter (": Visible"). FadeOut (500);//display hides $a. Parent (). Children (). EQ (i). FadeIn (1000);// Displays the picture//$ ("#banner") based on the value of the current LI element. css ("Background", "");//Displays the button style $ (this). Toggleclass ("show");//The current object is deleted or added class show $ (  This). Siblings (). Removeattr ("class");//Current Object delete Class Property});   Set timing or elimination timing T =setinterval ("ShowTime ()", 3000);//Run the method $ ("#banner") every three seconds. Hover (function ()}//Add mouse over event to button Clearinterval (t)},function () {//mouse over stop play T =setinterval ("ShowTime ()", 3000);//mouse slide out to continue playback});  }) function ShowTime () {if (n>= (count-1)) {n=0;  }else{N=++n; } $ ("#banner li"). EQ (n). Trigger (' click ');//code triggering click event}

Logical thinking:

This picture carousel code, broadly can be divided into three modules: initialization module, click event module, mouse hover module, self-active trigger module. The initialization module is intended to initialize the start-of-carousel picture ordinal. Clicking the time module is intended to determine that the Click event runs to display other object hidden actions. The mouse hover module is intended to clear or resume its own active trigger module in order to run the click operation. Self-triggering modules are used to simulate click events.

What's confusing about this code is that the settings I and n are global variables and run in functions and running statements. Trigger This event simulates the Click event, the mouse hover hover with the right advantage, will not cause a conflict with the Click event.

8. Select the City plugin

jQuery.fn.selectCity = function (targetobj) {var _self = this;//Gets the current object, using this plug-in selector object var targetobj = $ (targetobj);// Gets the object based on the This.click (function () {//Current object triggers the Click event var _top=$ (this). Offset (). Top + $ (this). Outerheight (True);  Gets the object relative to the top true height of Var _left=$ (this). Offset (). left;//gets the object relative to the left side is really highly targetobj.bgiframe ();//method of invoking Plug-in bgiframe () Targetobj.show (). css ({"position": "Absolute", "Top": _top+ "px", "left": _left+ "px"});//display positioning});//Depending on the location of the selected object, Hides the hidden display and sets the hidden bottom position targetobj.find ("#selectItemClose"). Click (function () {targetobj.hide ();//user clicks Close button to hide selection area}); Targetobj.find ("#selectSub: CheckBox"). Click (function () {Targetobj.find (": CheckBox"). attr ("checked", false);//  Set all the multi-marquee boxes to not be selected for $ (this). attr ("Checked", true);  _self.val ($ (this). Val ()); Targetobj.hide ();//settings click to select. and pass to input object value, hide check box});   $ (document). Click (Function (event) {if (event.target.id!=_self.selector.substring (1)) {//Mouse hides check box object when page is clicked)  Targetobj.hide (); } });    Targetobj.click (function (e) {e.stoppropagation ();//Stop event delivery}); return this;}

Logical thinking:

When a page clicks on an object, it sets the object that needs to be displayed to the bottom of the clicked object.

and set the Close button. The all multi-marquee setting is not selected. To select a specific column. When the mouse clicks on the page, the objects that need to be displayed disappear.

This is relatively novel when the mouse does not click on the display area and click on the object when the processing. To use a target.id inference to achieve the effect.

9. Paging plugin

Varpage_all = $ ('. Page ');//Gets all the areas that need to be paged, global variable Varuser_nav = $ (' #page_nation ');//user paging operation area. Global variables, in-function changes also change the value function Createactionlinks () {///Dynamic Component page Operation area user_nav.append (' <ahref= "javascript:void (0)" id= "prev  "> Previous page </a>"); For (vari=0;i<$ ('. Page '). length;i++) {//Display range Traversal user_nav.append (' <ahref= ' javascript:void (0) "class="  Numlink ">" + (i+1) + ' </a> '); } user_nav.append (' <ahref= ' javascript:void (0) "id=" Next "> Next </a>"); } function Changeaction (PAGE,PREBTN,NEXTBTN) {//Paging implementation function $ ('. Page:eq (' +page+ ') '). CSS (' Display ', ' block ');//Display current paging content $ (  '. Numlink:eq (' +page+ ') '). AddClass (' current ');//The active page button is highlighted varpagesize = parseint ($ ('. Page '). length-1);//Gets the maximum number of pages   if (page== 0) {//display on the first page prebtn.hide ();//Previous Button hidden Nextbtn.show ();//Next page button shows}else if (page==pagesize) {//display on last page Prebtn.show ();//prev button hides nextbtn.hide ();//Next page button shows}else{prebtn.show ();//Previous button shows Nextbtn.show ();//Next page B Utton}} function Hideobj () {page_all.css (' Display ', ' none ');//Hide AllPaging $ ('. Numlink '). Removeclass (' current ');//Remove all pagination style} $ (document). Ready (function () {$ ('. Page:eq (0) '). CSS (' Display '  , ' block ');//default display first page createactionlinks ();//Initialize Create user Action area $ ('. Numlink:eq (0) '). AddClass (' current ');//Add a style to the first button Varnextbtn= $ (' #next ');//Gets the next page of the button object VARPREBTN = $ (' #prev ');//Gets the previous page of the button object varlinkaction = $ ('. Numlink ');// Gets the collection of Hyperlink Objects prebtn.hide ();//Displays the first page by default and hides the previous action button Varpage =parseint ($ ('. Current '). Index ($ (') '));//Returns the page value, This sentence is very critical//three kinds of click action Nextbtn.click (function () {//To the next page button join Click event Hideobj ();//Hide All pagination part changeaction (page+1,prebtn,next  BTN);//function each time the value of the page is reduced by 1 page =parseint ($ ('.-Numlink '). Index ($ ('. Current ')));//Returns the value of the page}); Prebtn.click (function () {//Give previous page button join Click event Hideobj ();//Hide All pagination part changeaction (PAGE-1,PREBTN,NEXTBTN);// function each time the page value is added 1 page = parseint ($ ('. Numlink '). Index ($ ('. current '));//Returns the value of the page}) Linkaction.click (function () {// Add the page Number link to click event varthat = $ (this);//Get current Object Hideobj ();//Hide All pagination part varindex =that.index ()-1;//get current subscript value  Changeaction (INDEX,PREBTN,NEXTBTN);//Call paging Function page = parseint ($ ('. Numlink '). Index ($ ('. Current ')));//return page value})}) 

      Logical thinking:

Pagination belongs to the old growing talk, where the implementation is mainly from the paging button to generate the module, switch the page module, hide the module, and through ready. Initialize set the initial state, the corresponding button plus interactive operation is the Click event, and call the Switch page module to achieve click Switch.

Similar to the MVC architecture.

10. Note The key points for yourself to define plugins

(function ($) {$.fn.changetab = function (options) {//plugin needs to be attached to Jquery.fn object  var defaults = {   FontSize: "50px",   Color: ' Red ',   FontWeight: ' Bold '  }//sets the default number of parameters  var options = $.extend (defaults,options);//update  This.each (function () {   var lis = $ (this);//Keep this operation   lis.hover (function () {   $ (this). css ({"FontSize": Options.) FontSize, "Color": Options. Color, "fontweight": Options. FontWeight});   },function () {   $ (this). css ({"FontSize": "," "Color": "," FontWeight ": '}),   })}  }) (jQuery)///plug-in avoid using $, plug-ins should return a JQuery object for easy chaining operation  $ (function () {var options={FontSize: ' 16px ', Color: ' Blue ', fontweight : ' Bold '}//set personalization parameters $ (' li '). Changetab (options);//reference Plugin   })

Logical thinking:

1. The plugin needs to be attached to the JQUERY.FN.

2. Return jquery objects within the plugin for easy chain operation.

3. Set the default number of parameters and update the parameters by calling the Extend object.


The above summary of the project is the common effects of the situation, to see the event and selector is required to master a solid, some programming skills to learn.

Second This article can be used as a library. for use when viewing.


Front-end Programming Improvement Tour (II) jquery implementation of common effects----site

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.