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

Source: Internet
Author: User

The best programming language is logic, the front-end various interactive effects can be realized by jquery, special effects can be swirling, the internal logic is basically unchanged. This article focuses on the logic behind jquery for common effects.

1. Get the collection of elements through the class name

First of all, a JS native code does not support the method, through the class to get the collection of elements.

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;} Returns an array of all specified class names by traversing the entire document element class name

Logical thinking:

By constructing a regular expression of a class name, all tags are selected and matched with all label class name attributes through regular expressions, thus returning a class an array group to achieve the target of the set of elements through the class name.

The implementation of this method also gives the convenience of selecting elements of a particular ordinal without using jquery.

2. Construction of two-level linkage menu

$ ("#select1"). Change (function () {//Detect the Change event of a level menu  var id = $ ("#select1"). Val ();  if (id = = 1) {//ID Two-level menu   $.get (' index.php ', NULL, function (data) {//get-way 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 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 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 the Default option button style   $ (this). AddClass ("tab"); Adds   a style of $ ("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);//Remove time event when user mouse is removed   });});  /links corresponding to the corresponding content of the hidden and display

Logical thinking:

Here we first use $ () in which to write the function, here is a detailed description of the scope of application of the jquery constructor. By traversing each navigation link, when the mouse moves over the corresponding element, first remove all default option styles, plus the default check style on the hover element. and remove the current display style, set default options for the content style to display state.

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

4. Implementation of the "Show more" feature

$ (function () {var $hideObj = $ (' ul li:gt (5): not '),///Select the LI element with index greater than or equal to 5, remove the last one, and hide the $hideobj.hide (); $ ('. ShowMore Span '). Click (function () {if (! $hideObj. Is (": visible")) {//To determine 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, and then partially determine whether to display, show or hide

Logical thinking:

This first uses the selector to remove the last element with all LI elements greater than 5 selected. Through the user click the event, determine whether to show or hide, and linkage to modify the clicked icon.

The highlight of the selector is just right, with jquery the most basic need to use the cooked selector, which will quickly and efficiently manipulate the DOM node. It's easy to understand why CSS3 is the first to reform the selector, simplifying the operation flow, regularization, and semantic CSS selectors, making it easier for front-end engineers 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 modify the remaining words in real time});

Logical thinking:

Logic is very simple, get the focus remaining words display, lose focus remaining word 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 better experience. 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 stands for mouse events, mouse properties Pagex and Pagey represent the coordinates of the mouse position. The overall idea is to trigger a hover event with the mouse to display or remove a picture that has an offset from the mouse position and to move 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 that the first element is hidden by $ (" #banner li "). Click (function () {///To add a clicking event to the list of pictures Vari =$ (this   ). Text ()-1;//Gets the value within the LI element, that is, the value of 1,2,3,4 N =i;//i is assigned to n if (I >= count) {//is judged to be greater than the total number of a label 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", "");//Display button style $ (this). Toggleclass ("show");//Current Object delete or add Class show $ (this)  . siblings (). Removeattr ("class");//Current Object delete Class Property});   Set timing or elimination timing T =setinterval ("ShowTime ()", 3000);//Execute 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, can be divided into three modules: initialization module, click event module, mouse hover module, automatic trigger module. The initialization module is intended to initialize the start of the Carousel picture ordinal, click the time module is intended to determine that the click event execution is clicked to show other object hiding actions, the mouse hover module is intended to clear or resume the automatic triggering module, in order to perform the click action, the Auto trigger module is used to simulate the Click event.

What's confusing about this code is that the settings I and n are global variables, moving in and out of functions and execution statements. Trigger This event simulates a click event, the mouse hover hover is just right, and does 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 This.click (function () {//current object) based on the parameter _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 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 the Close button to hide the 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 ();//Set 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. Leave all multi-marquee settings unchecked to select a specific column. When the mouse clicks the page, the object that needs to be displayed disappears.

here is relatively new is when the mouse does not click on the display area and click on the object when the processing, only adopted a target.id judgement to achieve the effect.

9. Paging plugin

Varpage_all = $ ('. Page ');//Get all areas that need paging, global variable Varuser_nav = $ (' #page_nation ');//user paging operation area, global variable, function change also change value function  Createactionlinks () {//Dynamic Component page Operation area user_nav.append (' <ahref= "javascript:void (0)" id= "prev" > Previous </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 Highlights Varpagesize = parseint ($ ('. Page '). length-1);//Gets the maximum number of pages if ( page== 0) {//display on the first page prebtn.hide ();//prev button hide Nextbtn.show ();//The next page button shows}else if (page==pagesize) {//displayed on the last page Prebtn.sho W ();//Prev-page button hides nextbtn.hide ();//The next-page button shows}else{prebtn.show ();//The Previous button shows Nextbtn.show ();//Next-page button displays}} function hideob J () {page_all.css (' Display ', ' none ');//Hide All Paging $ ('. Numlink '). RemoveclasS (' current ');//Remove all pagination style} $ (document). Ready (function () {$ ('. Page:eq (0) '). CSS (' Display ', ' block ');//Display first page by default Createactionlinks ();//Initialize Create user Action area $ ('. Numlink:eq (0) '). AddClass (' current ');//Add a style to the first button varnextbtn= $ (' #next ');// Gets the next-page button Object varprebtn = $ (' #prev ');//Gets the previous-page button object varlinkaction = $ ('. Numlink ');//Gets a collection of Hyperlink objects prebtn.hide ();/ By default, the first page is displayed and the previous action button is hidden Varpage =parseint ($ ('.. numlink '). Index ($ ('. Current ')));//Returns the currently paged value, this sentence is critical//three click action Nextbtn.click ( function () {///to the next Page button add click event Hideobj ();//Hide All pagination part changeaction (PAGE+1,PREBTN,NEXTBTN);//function each time the value of page is reduced by 1 page =parsei  NT ($ ('. Numlink '). Index ($ ('. Current ')));//Returns the value of the page}); Prebtn.click (function () {//Give previous page button add click event Hideobj ();//Hide All pagination part changeaction (PAGE-1,PREBTN,NEXTBTN);// The function executes the value of the page each time plus 1 page = parseint ($ ('. Numlink '). Index ($ ('. current '));//Returns the value of the page}) Linkaction.click (function () {// Add Click event to page Number link Varthat = $ (this);//Get current Object Hideobj ();//Hide All pagination part varindex =that.index ()-1;//get current subscript value changeaction (in DEX,PREBTN,NEXTBTN);//Call the Paging function page= parseint ($ ('. Numlink '). Index ($ ('. Current ')));//return page value})}) 

  Logical thinking:

Pagination belongs to the old growth talk, here the implementation of the main from the paging button generation module, switch 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. Custom Plugin Note points

(function ($) {$.fn.changetab = function (options) {//plugin needs to be attached to Jquery.fn object  var defaults = {   FontSize: "50px",   Color: ' Red ',   FontWeight: ' Bold '  }//set default parameter  var options = $.extend (defaults,options);//Parameter 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 parameters and invoke the Extend object to update the parameters by passing the parameter.


The above summary of the project is the common effects of the situation, you can see that 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 viewing when you use it.


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.