Improvement of front-end programming (2) ---- jquery implementation of common website Special Effects
The best programming language is logic. jquery can be used to implement various interactive effects on the front end. Special effects can be varied, while the internal logic remains unchanged. This article describes the logic behind jquery's Implementation of Common special effects.
1. Get the element set by Class Name
First, let's look at a method that is not supported by js native code. It uses classes to get element sets.
Document. getElementsByClassName = function (classname) {var retnode = []; var myclass = new RegExp ('\ B' + classname + '\ B '); // match the class name var elem = this. getElementsByTagName ('*'); // obtain 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 file element Class Name
Logic:
By constructing a regular expression for a class name, Selecting All tags, and matching all tag class name attributes through a regular expression, an array of class names is returned, achieve the goal of getting the element set through the class name.
This method also facilitates the selection of elements with a specific ordinal number without jquery.
2. Structure of level-2 linkage menu
$ ("# Select1 "). change (function () {// detects the change event var id of a level-1 menu =$ ("# select1 "). val (); if (id = 1) {// identify level-2 menus by id $. get ('index. php ', null, function (data) {// get method to pass the value $ ("span "). empty (); // clear the tag $ ("span "). append ("JinanQingdaoLinyi"); // Fill in the corresponding level-2 menu});} else {$. get ('index. php ', null, function (data) {// get method to pass the value $ ("span "). empty (); // clear the tag $ ("span "). append ("ZhengzhouAnyangLuoyang"); // Fill in the corresponding level-2 menu });}});
Logic:
If the element value of the Linkage menu needs to be set to be changed, use the ajax method to pass a null value to its own page and append the corresponding element. Here is the level-2 menu. Here two jquery methods are used: the change method and the empty method.
The change method is triggered when the selected tag value changes. The empty method clears the html content in the tag.
3. Hide the link style and link content
$ (Function () {$ ("li "). each (function (index) {// traverse the user control area $ (this ). mouseover (function () {// obtain the id of the region selected by the current user = setTimeout (function () {// use the time event function for better user experience $ ("li. tab "). removeClass ('tab '); // remove the style of the default option button $ (this ). addClass ("tab"); // Add a style to the current Option Button $ ("div. show "). removeClass ('show '); // remove the style of the default display area $ ("# tab1 div: eq (" + index + ")"). addClass ('show'); // Add a style based on the selected index}, 300 );}). mouseout (function () {clearTimeout (id); // The time event is removed when the user moves the mouse}) ;}); // hide and display the corresponding content of The Link
Logic:
$ () Is used to write functions. The applicability of jquery constructor is described in detail here. By traversing each navigation link, when you move the mouse over the corresponding element, first remove all default option styles and add the default selected styles to the floating element. Remove the current display style and set the content style corresponding to the default options to display.
The highlight of this article is the use of a default display style of easing effect, the user experience is more meticulous.
4. Implementation of the "show more" Function
$ (Function () {var $ hideObj = $ ('ul li: gt (5): not (: last) '); // select the li element whose index is greater than or equal to 5, remove the last one and hide $ hideObj. hide (); $ ('. showmore span '). click (function () {if (! $ HideObj. is (": visible") {// determines whether the is method is visible $ hideObj. show (); $ ('. showmore span'mirror.css ("background", "url (. /images/up.bmp) no-repeat 0-10 "); // change the image status} else {$ hideObj. hide (); $ ('. showmore span'mirror.css ("background", "url (. /images/down.bmp) no-repeat 0 0 "); // change the status picture}); // select a part to hide it and check whether it is displayed, show or hide
Logic:
Here, the selector is used to remove all the li elements with the last element greater than 5. You can click an event to check whether the event is displayed or hidden, and modify the clicked icon.
The highlights are that the selector is well controlled. The most basic component of jquery should be familiar with the selector, which will quickly and efficiently operate dom nodes. In this way, it is not difficult to understand why css3's primary reform is the selector, which simplifies the operation process, regularization, and semantic css selector, making it easier for front-end engineers to read and write code.
5. "remaining words" in the text field"
$ (Document ). ready (function () {vartarea =$ ("# init"); // tarea. focus (function () {$ ("# numtj "). fadeIn (200 );}). blur (function () {$ ("# numtj "). fadeOut ("slow");}) // display or disappear the remaining words in the text field for getting the focus and losing the focus, and use the "fade in and 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 });
Logic:
The logic is very simple. The remaining words of the focus are displayed, and the remaining words of the focus are lost. Press the keyboard to calculate the remaining words.
The highlight here is that it is more natural to use the fadeIn and fadeOut methods to achieve a more natural and better experience. The focus and blur events are also common events that need to be processed by elements with input content. The keyup event is related to the user input and real-time interaction.
6. Move the mouse to enlarge the image
VarShowImage = function () {xOffset = 10; yOffset = 30; $ ("# imglist "). find ("img "). hover (function (e) {// Add events and trigger functions to image objects $ (""). appendTo ("body"); // Add an image object to the body $ ("# imgshow "). css ("top", (e. pageY-xOffset) + "px") // locate the y coordinate of the image displayed in the body, and add the offset manually. css ("left", (e. pageX + yOffset) + "px") // locates the body display chart. fadeIn ("fast") ;}, function () {$ ("# imgshow "). remove () ;}); $ ("# imglist "). find ("img "). mousemove (function (e) {$ ("# imgshow" example .css ("top", (e. pageY-xOffset) + "px "). css ("left", (e. pageX + yOffset) + "px ");});};
Logic:
The logic of this code is very universal. e Represents the table mouse event, and the mouse attributes pageX and pageY represent the coordinates of the mouse. The overall idea is to trigger a floating event with the mouse, display or remove an image that is at an offset from the mouse position, and move the enlarged image position in real time by setting the mousemove event.
After reading the above examples, we will find that events and selectors are the core of the overall interaction effect. Therefore, it is necessary to be proficient again.
7. Image carousel
Vart = 0; varn = 0; varcount; // global variable communication function and click event variable $ (document ). ready (function () {count = $ ("# bannerList "). length; // obtain the total number of user-controlled a tags $ ("# bannerList a: not (: first-child )"). hide (); // hide $ ("# banner li") except the first element "). click (function () {// Add a click event vari =$ (this) to the list of saved images ). text ()-1; // obtain the value in the Li element, that is, 1, 2, 3, 4 n = I; // The value of I is assigned to n if (I> = count) {// determine whether the total number of a tags is greater than return;} var $ a = $ ("# bannerLista "). filter (": visible "). fadeOut (500); // hide all displayed $. parent (). children (). eq (I ). fadeIn (1000); // display the image based on the current li element value // $ ("# banner" ).css ("background ",""); // display button style $ (this ). toggleClass ("show"); // Delete the current object or add a class show $ (this ). siblings (). removeAttr ("class"); // Delete the class attribute of the current object}); // set the timing or remove the timing t = setInterval ("showTime ()", 3000 ); // execute the method once every three seconds $ ("# banner "). hover (function () {// Add the mouse over event clearInterval (t)} to the button, function () {// move the mouse over to stop playing t = setInterval ("showTime ()", 3000); // move the mouse out to continue playing});}) function showTime () {if (n >=( count-1) {n = 0 ;} else {n = ++ n ;}$ ("# banner li "). eq (n ). trigger ('click'); // code triggers the click Event}
Logic:
This image carousel code can be divided into three modules: initialization module, click event module, mouse suspension module, and automatic trigger module. The initialization module is intended to initialize the sequence number of carousel images. The clicking time module is intended to confirm that the clicked event is performed to show other hidden objects. The mouse suspension module is intended to clear or resume the automatic trigger module, to perform the click operation, the automatic trigger module is used to simulate the click event.
This code is confusing because the I and n values are global variables, which are used in the middle of functions and execution statements. The trigger event simulates the click event. The mouse hover is used properly, so it does not cause a conflict with the click event.
8. Select the city plug-in
JQuery. fn. selectCity = function (targetObj) {var _ self = this; // gets the current object. Use the var targetObj =$ (targetObj) object in the selector of this plug-in ); // obtain the object this. click (function () {// trigger of the current object click Event var _ top = $ (this ). offset (). top + $ (this ). outerHeight (true); // obtain the true height of the object relative to the top var _ left = $ (this ). offset (). left; // obtain the height of the object to the left. targetObj. bgiframe (); // call the plug-in method bgiframe () targetObj.show().css ({"position": "absolute", "top": _ top + "px", "left ": _ left + "px "});/ /Show positioning}); // display hidden objects and set the hidden position below targetObj based on the position of the selected object. find ("# selectItemClose "). click (function () {targetObj. hide (); // click the close button to hide the selected region}); targetObj. find ("# selectSub: checkbox "). click (function () {targetObj. find (": checkbox "). attr ("checked", false); // set all multiple selection boxes to unselected $ (this ). attr ("checked", true); _ self. val ($ (this ). val (); targetObj. hide (); // click to select and pass it to the input object value to hide the selected box}); $ (document ). click (function (event) {if (ev Ent.tar get. id! = _ Self. selector. substring (1) {// hide the check box object targetObj when you click on the page. hide () ;}}); targetObj. click (function (e) {e. stopPropagation (); // block event transfer}); return this ;}
Logic:
When you click an object on the page, set the object to be displayed to the bottom of the clicked object. And set the close button. If you do not select all multiple selection boxes, select a specific column. When you click the page, the object to be displayed disappears.
The novelty here is that when the mouse does not click the display area and the processing of the clicked object, a target. id is used to determine the effect.
9. Paging plug-in
Varpage_all = $ ('. page '); // obtain all the regions that need to be displayed by page, the global variable varuser_nav =$ (' # page_nation '); // the user's paging operation region, the global variable, function createActionLinks () {// dynamically generates the paging operation region user_nav.append ('previous page'); for (vari = 0; I <$ ('. page '). length; I ++) {// traverse user_nav.append (''+ (I + 1) +'') within the range of the display area;} user_nav.append ('Next page ');} function changeAction (page, preBtn, nextBtn) {// implement the function $ ('. page: eq('{page}'{'}.css ('display', 'block'); // display the content of the current page $ ('. numlink: eq ('+ page + ')'). addClass ('current'); // the current page button highlighted varpageSize = parseInt ($ ('. page '). length-1); // obtain the maximum number of pages if (page = 0) {// display preBtn on the first page. hide (); // the previous page button hides nextBtn. show (); // next page button display} else if (page = pageSize) {// display preBtn on the last page. show (); // the previous page button hides nextBtn. hide (); // displayed on the next page} else {preBtn. show (); // display nextBtn on the previous page. show (); // next page button display} function hideObj () {page_all.css ('display', 'None'); // hide all pages $ ('. numlink '). removeClass ('date'); // remove all paging styles} $ (document ). ready (function () {$ ('. page: eq(0w.'demo.css ('display', 'block'); // the first page of createActionLinks () is displayed by default; // initialize the operation region for creating a user $ ('. numlink: eq (0 )'). addClass ('current'); // Add the style varnextBtn =$ ('# next') to the first button '); // obtain the next page button object varpreBtn =$ ('# prev'); // obtain the previous page button object varlinkAction =$ ('. numlink'); // gets the preBtn set of Hyperlink objects. hide (); // by default, the first page is displayed and the previous page OPERATION button varpage = parseInt ($ ('. numlink '). index ($ ('. current '); // returns the current page value. This sentence is critical. // three click actions nextBtn. click (function () {// Add the event hideObj () to the next page. // hide the changeAction (page + 1, preBtn, nextBtn) of all pages ); // The value of the page executed by the function minus 1 page = parseInt ($ ('. numlink '). index ($ ('. current '); // return page value}); preBtn. click (function () {// Add the event hideObj () to the previous page button; // hide the changeAction (page-1, preBtn, nextBtn) of all pages ); // Add 1 page = parseInt ($ ('. numlink '). index ($ ('. current '); // return page value}) linkAction. click (function () {// Add a click event varthat = $ (this) to the page number link; // obtain the current object hideObj (); // hide all paging part varindex = that. index ()-1; // obtain the current value changeAction (index, preBtn, nextBtn); // call the paging function page = parseInt ($ ('. numlink '). index ($ ('. current '); // return page value })})
Logic:
Paging is an old growth point. The implementation here mainly involves generating modules, switching pages, hiding modules, and initializing and setting the initial status through the paging button, add an interactive operation to the corresponding button, that is, the click event, and call the switch page module to achieve click switching. Similar to the MVC Architecture.
10. Considerations for custom plug-ins
(Function ($) {$. fn. changeTab = function (options) {// Add the plug-in to jquery. var defaults = {FontSize: "50px", Color: 'red', FontWeight: 'bold '} // set the default parameter var options = $. extend (defaults, options); // update this for the parameter. each (function () {var lis = $ (this); // retain this operation lis. hover (function () {detail (this).css ({"fontSize": options. fontSize, "color": options. color, "fontWeight": options. fontWeight}) ;}, function () {detail (this).css ({"fontSize": ''," color ":'', "fontWeight ": ''});}) (jQuery) // avoid using $ in the plug-in. The plug-in should return a jquery object to facilitate chained operations $ (function () {var options = {FontSize: '16px ', Color: 'blue', FontWeight: 'bold'} // set the personalized parameter $ ('lil '). changeTab (options); // reference ins })
Logic:
1. The plug-in must be attached to jquery. fn.
2. jquery objects returned in the plug-in are easy to perform chained operations.
3. Set the default parameter and call the extend object to update the parameter by passing the parameter.
The above summary is a common special effect scenario in the project. We can see that the event and Selector need to be well mastered, and some programming skills should also be learned. Next, this article can be used as a library for viewing during use.