Learn jquery from scratch (vii) jquery animation implementation let the page move _jquery

Source: Internet
Author: User
Tags numeric numeric value visibility

I. Summary

This series of articles will take you into the wonderful world of jquery, with many authors ' specific experiences and solutions, even if you can use jquery to find some cheats in your reading.

The developer has been doing animation with pain. But with jquery you will instantly become the animation master in the eyes of others (those who don't know jquery)! This article describes the animation-related functions of jquery. The original animation is so simple!

Two. Foreword

Examples of this series of articles are for a particular technical detail, because we want to learn is the basic knowledge, although there are always some people want to be more complex application examples, but I think let us first of the foundation, with a solid foundation with everyone's wisdom will be able to create more and better applications.

Just a few days before writing this article, there were more than one colleague who was worried about the "pop-up layer" effect. But in the future to face such a function to see this article each person can be happy smile. JQuery, make work easy!

Three. Start with the example

Do Web programs often use a pop-up layer, such as clicking Text or buttons to display a hint of text and so on. The following requirements are assumed:

    • Click the Show hint Text button in the diagram to display a pop-up layer below the button.
    • Click any blank area or pop-up layer and the pop-up layer disappears.

With primitive JavaScript We can also complete this work. There are several things to note:

1. The position of the pop-up layer needs to be calculated dynamically. Because the object that triggers the pop-up event may appear anywhere on the page, such as the position in the screenshot.

2. For document binding Click is the function to turn off the pop-up layer, to use multicast delegates, or you may flush other people in the document binding functions.

3. After the closed function is bound for document, the event bubbling is required to be canceled in the display function, or the pop-up layer will be turned off immediately after it is displayed.

With jquery, we can easily implement this example:

&lt;!DOCTYPE Html Public "-//w3c//dtd XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;Html xmlns= "Http://www.w3.org/1999/xhtml"&gt; &lt;Head&gt; &lt;Title&gt;Jquery-start Animation&lt;/Title&gt; &lt;Script Type= "Text/javascript" Src=".. /scripts/jquery-1.3.2-vsdoc2.js "&gt;&lt;/Script&gt;&lt;script type="Text/javascript"&gt; $ (document) Ready (function() {Animation speed VarSpeed = 500;Binding Event Handling$("#btnShow"). Click (function(Event) {Cancel Event Bubbling Event. Stoppropagation ();Setting the pop-up layer location VarOffset = $ (Event. Target). offset (); $("#divPop"). css ({top:offset.top + $ (Event. Target). Height () +"PX", left:offset.left});Animated display$("#divPop"). Show (speed); });Click a blank area to hide the pop-up layer$ (document). Click (function(Event) { $("#divPop"). Hide (Speed)});Click the pop-up layer to hide itself$("#divPop"). Click (function(Event) { $("#divPop"). Hide (Speed)}); });&lt;/Script&gt; &lt;/Head&gt; &lt;Body&gt; &lt;Div&gt; &lt;Br /&gt;&lt;Br /&gt;&lt;Br /&gt; &lt;button Id= "Btnshow"&gt;Display prompt text&lt;/button&gt; &lt;/div> <--> div id= "Divpop" style= " Background-color: #f0f0f0; Border:solid 1px #000000; Position:absolute; Display:none; width:300px; height:100px; " > <div style = "Text-align:center;" > pop-up layer </div> </div> body> >               

In addition to achieving the basic display and hide features, now show and hide the pop-up layer is a gradient animation effect! the animation function of jquery is so simple that the first time I used it in my project I was pleasantly surprised. I used to compute the location of a headache across browsers, but the offset () function and the height () function of jquery allow you to accurately compute the position of the pop-up layer.  These functions are encapsulated and cross-browser. Need to be aware of when setting the pop-up layer position attribute, plus "px", otherwise it is easy to appear under the Firefox problem.

jquery's animated functions fall into three main categories:

    1. Basic Animation function: Both transparency gradient and sliding effect. Is the most commonly used animation effect function.
    2. Slide animation function: Only sliding gradient effects are used.
    3. Fade animation function: Use only transparency gradient effects.

These three kinds of animation function effects are different, the usage is basically consistent. Everyone can try it on their own.

In addition, perhaps the above three function effects are not what we want, then jquery also provides the custom animation function, puts the control right in our hand lets us define the animation effect.

The following three types of built-in animation functions and custom animation functions are explained separately.

Four. Basic animation function


The show () and hide () used in the example above are the basic animation functions we use most.

Here's the basic jquery animation function:

Basic Animation Function Basics

Name Description Example
Show ()

Displays hidden matching elements.

This is the ' Show (speed, [callback]) ' version without animation. If the selected element is visible, this method will not change anything. This method works regardless of whether the element is hidden by the Hide () method or if the Display:none is set in CSS.

Show all paragraphs:
$("p").show()
Show (speed, [callback])

Displays all matching elements in an elegant animation and optionally triggers a callback function after the display is complete.

The height, width, and opacity of each matching element can be dynamically changed according to the specified speed. In jquery 1.3, padding and margin also have animations that work more smoothly.

Display hidden paragraphs with slow animations, lasting 600 milliseconds:
$("p").show(600);
Hide ()

Hide the displayed elements

This is the "Hide (speed, [callback])" of the No animation version. If the selected element is hidden, this method will not change anything.

Hide all paragraphs:
$("p").hide()
Hide (speed, [callback])

Hides all matching elements with graceful animations and optionally triggers a callback function after the display is complete.

The height, width, and opacity of each matching element can be dynamically changed according to the specified speed. In jquery 1.3, padding and margin also have animations that work more smoothly.

To hide a paragraph slowly in 600 milliseconds:
$("p").hide("slow");
Toggle ()

Toggles the visible state of the element.

If the element is visible, switch to hidden, and if the element is hidden, toggle to visible.

Toggle the visible state of all paragraphs:
$("p").toggle()
Toggle (Switch)

Toggles the visible state of the element according to the switch parameter (ture is visible and false is hidden).

If the switch is set to True, the show () method is invoked to display the matching element, and hide () is called to conceal the element if the switch is set to False.

Toggle the visible state of all paragraphs:
var flip = 0;
$("button").click(function () {
   $("p").toggle( flip++ % 2 == 0 );
});
Toggle (speed, [callback])

Toggles all matching elements in an elegant animation and optionally triggers a callback function after the display is complete.

The height, width, and opacity of each matching element can be dynamically changed according to the specified speed. In jquery 1.3, padding and margin also have animations that work more smoothly.

Quickly toggle the paragraph in 200 milliseconds to show the status, and then a dialog box pops up:
$("p").toggle("fast",function(){
  alert("Animation Done.");
 });


1. Using basic animation functions

Basic animation functions are mainly divided into show, hide and toggle three. Provides a parameter-free version that indicates that the display state of the animation toggle element is not applicable:

$ ("#divPop"). Show ();
$ ("#divPop"). Hide (); $ ("#divPop"). Toggle ();  



Provides an overload of two parameters, because the callback function can be omitted, so you can use a numeric value as a unique argument, as used in the opening instance, to animate/hide elements in the time specified by the parameter:

$ ("#divPop").
$ ("#divPop"). Hide ("fast"); $ ("#divPop"). Toggle ("slow");    

If 200 is passed, the layer is displayed as a gradient in 200 milliseconds. The speed parameter can use either a string of three predetermined speeds ("slow", "normal", or "fast") or a millisecond value that represents the length of the animation (for example, 1000).

Three functions can be passed in the callback function callback, signed as follows:

function callback () {
 //DOM element}


This is the DOM object that executes this function in the callback function. is executed at the end of the animation.

2. Using the Toggle function

The toggle function is a more powerful function that toggles the visible state of an element. We often encounter situations where we need to use toggle. For example, if you want a text to click the pop-up layer for the first time, click Hide the pop-up layer for the second time.

We can do this by slightly modifying the opening example:

&lt;!DOCTYPE Html Public "-//w3c//dtd XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;Html xmlns= "Http://www.w3.org/1999/xhtml"&gt; &lt;Head&gt; &lt;Title&gt;JQuery Animation-toggle&lt;/Title&gt; &lt;Script Type= "Text/javascript" Src=".. /scripts/jquery-1.3.2-vsdoc2.js "&gt;&lt;/Script&gt;&lt;script type="Text/javascript"&gt; $ (document) Ready (function() {Animation speed VarSpeed = 500;Binding Event Handling$("#btnShow"). Click (function(Event) {Cancel Event Bubbling Event. Stoppropagation ();Setting the pop-up layer location VarOffset = $ (Event. Target). offset (); $("#divPop"). css ({top:offset.top + $ (Event. Target). Height () +"PX", left:offset.left});Toggle the display status of the pop-up layer$("#divPop"). Toggle (speed); }); });&lt;/Script&gt; &lt;/Head&gt; &lt;Body&gt; &lt;Div&gt; &lt;Br /&gt;&lt;Br /&gt;&lt;Br /&gt; &lt;button Id= "Btnshow"&gt;Hint text&lt;/button&gt; &lt;/div> <--> div id= "Divpop" style= " Background-color: #f0f0f0; Border:solid 1px #000000; Position:absolute; Display:none; width:300px; height:100px; " > <div style = "Text-align:center;" > pop-up layer </div> </div> body> >               


The toggle () function can pass an argument for a Boolean value, for example: Toogle (True) is equivalent to show (), and Toogle (Fasle) is equivalent to hide ().


Five. Slide animation function


The effect of the basic animation function is a function that combines the sliding and transparency gradients, and jquery also provides a single correlation function that only has a sliding effect.

Sliding animation function Sliding

Name Description Example
Slidedown (speed, [callback])

Dynamically displays all matching elements by changing height (increasing downward), optionally triggering a callback function after the display is complete.

This animation effect only adjusts the height of the elements, allowing the matching elements to be displayed in a "sliding" manner. In jquery 1.3, padding and margin can also be animated and have a smoother effect.

Slide the paragraph down slowly with 600 milliseconds:
$("p").slideDown("slow");
Slideup (speed, [callback]) Dynamically hides all matching elements by changing the height (decreasing upwards), optionally triggering a callback function after the shadowing is complete. Slide the paragraph 600 milliseconds slowly:
$("p").slideUp("slow");
Slidetoggle (speed, [callback]) Toggles the visibility of all matching elements by changing the height, and optionally triggers a callback function after the switch completes. Slide the paragraph up or down with a slow 600 millisecond:
$("p").slideToggle("slow");

Explain

Slidedown is the slide effect version of Show, Slideup is the sliding effect version of hide, Slidetoggle is toggle's slide effect version.

The parameters are exactly the same:

$ ("#divPop"). Slidedown (m);
$ ("#divPop"). Slideup ("fast"); $ ("#divPop"). Slidetoggle ("slow");    

Six. Fade and fade animation function

The Fade out function provides only the effect of a transparency gradient.

Fade function Fading

Name Description Example
FadeIn (speed, [callback])

The fading effect of all matching elements is achieved by changing the opacity, and optionally triggering a callback function after the animation completes.

This animation only adjusts the opacity of the element, which means that the height and width of all matching elements do not change.

Fade the paragraph in 600 milliseconds slowly:
$("p").fadeIn("slow");
Fadeout (speed, [callback]) The fade effect of all matching elements is realized by the change of opacity, and a callback function is optionally triggered after the animation completes. Slowly fade the paragraph with 600 milliseconds:
$("p").fadeOut("slow");
Fadeto (speed, opacity, [callback]) Adjusts the opacity of all matching elements incrementally to the specified opacity and optionally triggers a callback function after the animation completes. With 600 milliseconds to slowly adjust the transparency of the paragraph to 0.66, about 2/3 of the visibility:
$("p").fadeTo("slow", 0.66);$("p").fadeTo("slow", 0.66);

Explain

The Fadein and fadeout two functions correspond to show and hide, which are used to display and hide objects with the effect of transparency gradients:

$ ("#divPop"). FadeIn (m);
$ ("#divPop"). Fadeout ("fast");  

The transparency gradient does not have a switch function.

What needs to be specifically explained is the Fadeto function. This function allows the object to be gradient to the specified transparency. The opacity parameter takes a value from 0-1, such as 0.6, to indicate a transparency of 60%.

Unlike Fadein and fadeout, the fadeto function only changes the transparency of the object, even if the transparency is 0 objects still in place. and Fadein and fadeout will eventually change the display property of the object, fadeout the object will disappear from the page (not occupy), but Fadeto just make it transparent (placeholder).

The Fadeto function can be used in conjunction with Fadein. For example, by default, Fadein finally lets the object display completely:

However, if you have previously used Fadeto to set the transparency of the pop-up layer, you can make it translucent:

The core code is as follows:

 //set the transparency of the pop-up layer $ ( "#divPop"). Fadeto (0, 0.66); N class= "rem" >//let the pop-up layer transparently display if ($ ( "#divPop"). CSS ( "display") = =  "none") {$ ( "#divPop"). FadeIn (speed); else {$ ( "#divPop"). Fadeout (speed);}       

After you set the pop-up layer transparency with Fadeto, using Fadein will let the object display and gradient to the transparency of the Fadeto setting.

Here are just two functions of the characteristics of the actual application does not necessarily need to use both.


Six. Animation Lab

The animation lab is an example of the "jquery Combat" book, which makes it easy to see the effects of the above three animations. The chapter7\lab.effects.html file corresponding to the source code. The source code is provided at the end of this article. The lab screenshot is as follows:


Seven. Custom Animation function

The above three gradient animation functions have basically satisfied our daily needs. But if we are sure to create our own special effects, jquery also provides us with the relevant functions.

Custom Animation function Custom

Name Description Example
Animate (params, [duration], [easing], [callback] ) //apply three types of effects in an animation
$ ("#go"). Click ( function () {
$ ("#block"). Animate ({
  width: "90%",
  Height: "100%",
  fontsize: "10em",   borderwidth:10
}, 1000);
});
Animate (params, options)

A function to create a custom animation. The key to the

function is to specify the animation form and the result style Property object. Each property in this object represents a style attribute that can be changed (such as "height", "top", or "opacity"). Note: All specified attributes must be in camel form, such as marginleft instead of Margin-left.

And the animation ends when the value of each property indicates how much of the style property is. If it is a numeric value, the Style property is graduated from the current value to the specified value. If you are using a string value such as hide, show, or toggle, the default animation form is invoked for the property.

In JQuery 1.2, you can use EM and% units. In addition, in JQuery 1.2, you can make the element relative motion by specifying " + + " or "-= " before the attribute value. The


$ ("#go1"). Click (function () {$ (#block1). Animate ({width:) 90% "}, {queue:false, duration:5000}). Animate ({fontsize: ' 10em '}, 1000). Animate ({Borderwidth:5}, 1000); }); $ ("#go2"). Click (function () {$ ("#block2"). Animate ({width: "90%"}, 1000). Animate ({fontsize: ' 10em '}, 1000). Animate ({borderwidth:5}, 1000); });
Stop ([Clearqueue], [gotoend])

Stops all animations that are running on the specified element.

If there is an animation waiting to be executed in the queue (and Clearqueue is not set to true), they will be executed immediately


Clearqueue(Boolean): If set to true, the queue is emptied. You can end the animation immediately.

Gotoend (Boolean): Let the currently executing animation complete immediately, and reset the original style of show and hide, call the callback function, and so on.

Click Go to start the animation, after the stop will stop at the current position:

// 开始动画
$("#go").click(function(){
 $(".block").animate({left: '+200px'}, 5000);
});

// 当点击按钮后停止动画
$("#stop").click(function(){
 $(".block").stop();
});

Parameter description

1.params (optional)

Type: Options

Description: A set of style attributes and their values that are included as animation properties and end values.

Explanation: Animate an element by adjusting the value of its style attribute from the current value to the value set by the params.

2.duration (optional)

Type: String,number

Description: A string of three predetermined speeds ("slow", "normal", or "fast") or a millisecond value representing the length of the animation (for example: 1000)

Explanation: The longer the animation effect lasts, the slower it becomes. If omitted, no animation is generated.

3.easing (optional)

Type: String

Description: The name of the erase effect to use (requires plug-in support). The default jquery provides "linear" and "swing".

Explanation: In order for the elements to gradually reach the final effect of the params setting, we need to have a function to implement the gradient, which is called the easing function. But the only easing function name that needs to be passed here is to register the easing function on jquery before using it.

4.options parameters

Type: Options

Description: A set of values that contain animation options.

Explanation: The supported properties are as follows:

    • Duration: Same as the duration parameter above
    • Easing: Same as the easing parameter above
    • Complete: Functions that are performed when the animation completes, type is a function
    • Step:callback
    • Queue (Boolean): (Default: TRUE) setting to False causes this animation to not enter the animation queue (new in JQuery 1.2)

Explain

Custom animations belong to advanced applications, where I am unable to explain them in detail. Here are two examples of how to use custom animations.

Bug Tip: The following two examples use the VSDOC2 smart-tip version of the JQuery class library to have a problem with transparency that cannot be graduated under Firefox. Please use a different version.

Custom Fall Animation:

This example lets a layer fall from the top of the screen to the bottom and disappears.

&lt;!DOCTYPE Html Public "-//w3c//dtd XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;Html xmlns= "Http://www.w3.org/1999/xhtml"&gt; &lt;Head&gt; &lt;Title&gt;JQuery Animation-fadeto&lt;/Title&gt; &lt;Script Type= "Text/javascript" Src=".. /scripts/jquery-1.3.2.js "&gt;&lt;/Script&gt;&lt;script type="Text/javascript"&gt; $ (document) Ready (function() { $("#divPop"). Animate ({"Opacity":"Hide","Top": $ (window). Height ()-$ ("#divPop"). Height ()-$ ("#divPop"). Position (). Top}, 600,function() { $("#divPop"). Hide (); } ); });&lt;/Script&gt; &lt;/Head> <body> <div id= "Divpop" style=: #f0f0f0; background-color 1px #000000; border:solid; height:100px; Position:absolute; " > <div style = "Text-align:center;" > pop-up layer </div> </div> body> >               

Custom Scatter Animation:

This example makes a div bigger and larger and finally disappears:

&lt;!DOCTYPE Html Public "-//w3c//dtd XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;Html xmlns= "Http://www.w3.org/1999/xhtml"&gt; &lt;Head&gt; &lt;Title&gt;JQuery Animation-fadeto&lt;/Title&gt; &lt;Script Type= "Text/javascript" Src=".. /scripts/jquery-1.3.2.js "&gt;&lt;/Script&gt;&lt;script type="Text/javascript"&gt; $ (document) Ready (function() { $("#divPop"). Animate ({"Opacity":"Hide","Width": $ (window). Width ()-100,"Height": $ (window). Height ()-100}, 500); });&lt;/Script&gt; &lt;/Head> <body> <div id= "divpop" style= "Background-color: #f0f0f0; Border:solid 1px #000000; width:300px; height:100px; Position:absolute; " > <div style= "text-align:center;" > Pop-up layer </div> </div> </body> </  HTML>                


Eight. Global control properties

Finally, let's talk about animation-related properties:

Name: JQuery.fx.off

return Value: Boolean

Description

Closes all animations on the page.

Explain:

Set this property to true to immediately turn off all animations (all effects are immediately completed). In some cases this may be necessary, such as:

* You use jquery on a computer with a lower configuration.

* Some of your users are experiencing accessibility problems due to animation effects

When you set this property to False, you can turn all animations back on.

For example, the following code performs a disabled animation:

true;
$ ("#divPop"). Show (1000);


Although the show function of the animation effect is used, because all animations are turned off, the DIV is immediately displayed without a gradient effect.



Nine. Summary

This article explains the three kinds of animation functions that jquery provides: basic animations, slide animations, and fade animations. Using these three kinds of animations has basically been able to meet our daily development needs and let our pages move. A simple example illustrates a custom animation. For those who want to study deeply, this article can only play a good effect.

code Download: http://xiazai.jb51.net/201101/yuanma/Code-jQueryStudy.rar

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.