If you seek answers from professionals with a single question, one of your questions will become three, because he will use the other two terms that make you more confused to explain your question.
I think this is the biggest problem that it people encounter during their learning, including me. When you have a piece of code or a concept that is not very clear, Baidu or Google or ask questions on the Forum, the answers are often mixed with more code that you don't understand and can cause headaches.
I also suffered the same loss and decided to make some conclusions on the animate aspect, hoping to give you some inspiration and help.
From a practical application
Today, we will not talk about animation functions such as animate (), fadeIn (), fadeOut (), slideUp (), show (), and hide (). Instead, we will talk about a few less commonly used animation functions, even a bit difficult, but very important animation functions queue (), dequeue (), and stop ().
Let's start with a simple example. Suppose there is a shopping function. Before the checkout, the user can still Delete the shopping cart to the option bar (maybe due to insufficient user funds, can be stored until the next purchase)
Well, based on the requirements described above, we abstracted the following layout. "origin" simulates the shopping cart, "goal" simulates the alternative column, and "object" simulates the item that may be deleted, the "change" button enables the exchange of items from the left and right
At the same time, we want to add an animation effect when the item is switched from left to right. We hope that there is an hide () Hidden effect on the left, tell the user that the item is no longer in the shopping basket. Then, the front end uses appendTo () to move the item to the right, and uses a show () effect to tell the user that the item has been transferred successfully. The procedure is as follows:
(On the left) Hide the object --> move the object from the left to the right --> show the object (on the right)
So we naturally come up with the following code:
$('#object').hide('slow').appendTo($('#goal')).show('slow');
And we put the code into practice, as shown below:
Origin
Object
Goal
Complete code in this example:
$('#test-change').toggle(function(){$('#test-object').hide('slow').appendTo($('#test-goal')).show('slow');},function(){$('#test-object').hide('slow').appendTo($('#test-origin')).show('slow');
After running, you will find that the results are not as expected. The object is first transferred, hidden, and then:
Move the object from the left to the right --> hide the object (on the right) --> show the object (on the right)
So the question is, it is clearly written in the order we reserve, but the result is not as expected. Why?
This is also the first actual example of my contact with queue () in my project. The answer below is the key after I post a question on the official jQuery forum (the original post is here ).
When you are using methods that animate content, those animations are added to what is called a queue, specifically the "fx" queue. normal jquery methods, such as prependTo (), are not added to the "fx" queue, therefore they get executed immediately instead of waiting till the previusly added item in the queue is executed.
What does it mean? That is to say, when you use a series of animation effects (such as hide and show), these animation functions will be put into a queue named "fx, then, the function in the queue is executed in the first-in-first-out mode, instead of the animation function. For example, the appendTo function in the above example will not enter the queue and be executed before the animation function, that is, before getting the first function from "fx", it has been executed.
So in the above example, we can see that the object is first transferred to the right, and then hidden and then displayed, that is, the appendTo function is first executed by the animation function.
After understanding the root cause of the disease, we need to take the right medicine-in the end, it's just a matter of order, as long as the appenTo is followed by the hide before the show operation, everything is fine. So we thought, can I add the appendTo function to the queue and the function is located between hide and show? In this way, the execution can be performed in order.
The answer is yes. Although the "fx" queue is a reserved animation function by default, there is nothing wrong with the manipulation function. To be precise, it is not just a manipulation function, jQuery provides the queue () function to insert some code you need into a queue. Why? In the following example, we can see that the queue can also be customized.
We will first change the above example to the desired effect, and then explain the queue Method Based on the code.
$('#object').hide('slow').queue(function(next){$(this).appendTo($('#goal'));next();}).show('slow');
In fact, you can see the code at a glance. We can understand it in this way (it is only helpful to understand its functions, not its essence). queue () is not a good one. It is a function that helps the queue, if you want to insert a function or a series of functions into several animations, put the function you want to insert into the function body of queue (), just like the code above, the parameters "next" and next () are used to ensure that the inserted function can continue to run the next animation function in the queue after the inserted function is executed. In the preceding example, show () is used ().
After modifying the code, we can achieve the desired effect, as shown below:
Container
Object
Goal
Complete code in this example:
$('#test-change1').toggle(function(){$('#test-object1').hide('slow').queue(function(next){$('#test-object1').appendTo($('#test-goal1'));next();}).show('slow');},function(){$('#test-object1').hide('slow').queue(function(next){$('#test-object1').appendTo($('#test-origin1'));next();}).show('slow');});
. Queue ()
Next, let's talk about the queue function.
Let's start with a simple example:
If you want to make a small div with a black background, first collapse (slideUp), put it down (SlideDown), and then turn the background into white, how should the statement be written?
Having learned the lessons of the previous example, I believe that such statements are not written in a naive order?
$('div').slideUp('slow').slideDown('slow').css({"background":"red"});
What should I do? Use the queue function! Brilliant!
$('div').slideUp('slow').slideDown('slow').queue(function(next){$('#object').css({"background":"red"});next();});
The actual example is not displayed on the page. This is a very simple code. You can imagine it.
Here I want to explain a few questions:
First of all, when jQuery officially elaborated on the. queue method, there was such an interesting sentence:
This feature is similar to providing a callback function with an animation method,
But does not require the callback to be given at the time the animation is already med.
We have to go back to the Function Definition of. queue (). In fact, we now add function usage in queue. The official function prototype is:
Queue ([queueName], callback (next ))
That is to say, the added function is actually a callback function about the queue. That is, after the queue ends, the system automatically calls the function you added.
In one sentence, what is a callback function? Baidu, you will know. The first article in the returned results is Baidu's explanation of the "callback function "..But as I mentioned at the beginning of this article, it does give you a very detailed explanation, but the premise is that you can digest the C ++ professional vocabulary and code ......Fortunately, my Unix Network Programming teacher (Hey, a doctor from Peking University) once gave us a very popular explanation and defined it by myself,System Call. The key to a callback function is that we cannot predict when it will be called.Because we just defined such a function, we may notify the system to call it after completing a series of actions.
In fact, we can consider this. If we use this function as the slideDown callback function, isn't it all the same? This is because all we want is to ensure that the color changing function is executed after slideDown. Both the slideDown and queue callback functions can ensure this effect! Look:
$('div').slideUp('slow').slideDown('slow',function(){$('#object').css({"background":"red"});});
It is just the same thing.
One more thing to note is whether or not the next parameter and next () in. queue () can be removed?
We mentioned above that the function in queue is a callback function. If we make some modifications to the above Code, for example:
$('div').slideUp('slow').slideDown('slow').queue(function(next){$('#object').css({"background":"red"});//next();}).hide('slow');
First, I commented out the next () statement, and the second was to hide the square after the color changes. However, after you run it, you cannot hide the blocks after the color changes.
Remember that the function in the queue is a callback function. By default, the color changing function is called only after the animation queue is executed. Where does the hide () function come from when all the animation queues are executed ()? So next () is to ensure that the next animation function is executed again after the queue is executed.
I have tried to discard the next parameter and keep the next () statement. This result can be run in modern browsers (such as firefox and chrome), but cannot be run in ie6. So keep it..Next and next () appear only in jquery1.4, And the. dequeue () function is used before. If you want to change the example in this section to dequeue (), as follows:
$('#object').slideUp('slow').slideDown('slow').queue(function(){$('#object').css({"background":"red"});$(this).dequeue();});
Custom queue
I have mentioned before that I can not use its default 'fx 'queue. This section teaches you how to customize a queue of your own, which is very simple:
I want to create a queue named 'custom', which contains a method to change the background color of a black box, as shown below:
$("div").queue("custom", function(next) { $('div').css({'background':'red'}); next();});
What you see is what you get -- the previous 'custom' represents the name of the new Queue (what if I also use 'fx? I don't know either. If you are interested, you can leave a message to tell me the result. I will also know if you are interested.) The callback function is still used to pile up the functions you want to execute.
But it's just this code. When you really add it to the webpage and try to run it, you will find that it is not "What you see is what you get", and it will not have any effect at all. Because I intentionally omitted the most critical statement ...... The modified information is as follows:
$("div").queue("custom", function(next) { $('div').css({'background':'red'}); next();}).dequeue("custom"); //this is the key
Yes, that is,. Dequeue ("custom "). Generally, dequeue () is defined as "deleting the top function in the queue and executing it ". I don't agree with the word "delete", but tend to "retrieve". In fact, this function is like a pointer to a queue in a data structure. After the previous function in the queue is executed, take the function at the top of the next queue.
Practice
OK. The main knowledge points are all described. Maybe you will ask, do we actually use such complex animation operations? I believe most people won't. animation is just a small embellishment on the webpage, but it's a safe journey. Here I will copy the queue application example on Cameron Mckay's blog.
Suppose you want this effect: Let an object float up 2000 milliseconds (2 seconds), and the object in the first 1000 milliseconds is completely opaque, and the object in the last 1000 milliseconds changes from completely opaque to completely transparent, to make it clearer, the following timeline table is provided (assuming that the object starts to be 100px from the top of the container, that is, top: 100px ;):
| Time (MS) |
Height from top |
Opacity |
| 0 |
100px |
1.0 |
| 500 |
90px |
1.0 |
| 1000 |
80px |
1.0 |
| 1500 |
70px |
0.5 |
| 2000 |
60px |
0.0 |
From the timeline table, we can see more clearly what we want. During this 2000 ms period, the height of the object changes evenly and gradually decreases, the opacity is always 1000 in the first 1.0 milliseconds, but is gradually reduced in the last 1000 milliseconds until it is completely 0.
If we only consider the floating and transparent effects for the moment, we may write the following statement:
$("#object").animate({opacity: 0, top: "-=40"}, {duration: 2000});
Unfortunately, such a statement can only make the object gradually convert to Opacity in 2000 milliseconds, that is, we cannot make it 1000 opaque in the first 100% milliseconds -- so we use queue to solve this problem:
$("#object").delay(1000, "fader").queue("fader", function(next) { $(this).animate({opacity: 0}, {duration: 1000, queue: false}); next();}).dequeue("fader").animate({top: "-=40"}, {duration: 2000})
Let's take a look at its idea: store the animation that controls opacity and upward movement in two queues respectively, and the queue that controls upward movement is implemented by default (within 2000 milliseconds ), the opacity is controlled to be executed within 1000 milliseconds, but the queue will be executed later than the default queue's 1000 milliseconds.
Simply put, the first 1000 milliseconds, only the "fx" queue with control height is executed, and the last 1000 milliseconds, the "fader" queue with control Opacity is in parallel with the "fx" queue with control height.
First, prepare two queues,
One is the default "fx", which stores highly changed animations:
.animate({top: "-=40"}, {duration: 2000})
The other is a custom "fader" queue to store animations with opacity changes:
.animate({opacity: 0}, {duration: 1000, queue: false});
Pay attention to the "queue: false" in the above Code. This is a key sentence to prevent this animate from entering the default "fx" queue.
Any animation effect will enter the "fx" queue, even if you define the animation in. queue (), and the animation effect must be executed in order, for example, the following code:
$('#object').slideUp(1000)
.slideDown(1000)
.animate({width: '50px'}, {duration: 1000});
After running, it will only be executed in order, first collapse, then put down, and then shrink the width to 50px
However, once I add the "queue: false" parameter:
$('#section3a').slideUp(1000).slideDown(1000).animate({width: '50px'}, {duration: 1000, queue: false});
You will find that the width of the object is also shrinking while the object is being reduced.
The slideUp, slideDown, and animate of linear execution are converted into the animations and slideUp and slideDown parallel operations:
The running result is as follows:
Complete code in this example:
function queuetrue(){$('#section3a').slideUp(1000).slideDown(1000).animate({width: '50px'}, {duration: 1000});}function queuefalse(){$('#section3a').slideUp(1000).slideDown(1000).animate({width: '50px'}, {duration: 1000, queue: false});}$("#section3a-input").click(function(){$("#section3a").css({'width':'100px'});queuetrue();});$("#section3b-input").click(function(){$("#section3a").css({'width':'100px'});queuefalse();});
Okay. Let's look back at this example:
$("#object").delay(1000, "fader").queue("fader", function(next) { $(this).animate({opacity: 0}, {duration: 1000, queue: false}); next();}).dequeue("fader").animate({top: "-=40"}, {duration: 2000})
In fact, the first three statements (the statements mentioned here are marked by ".") have done the following:
Defines a queue named fader, which is used to control opacity changes --. queue () Statement
Let it execute the --. delay () delay function after 1000 milliseconds to delay the execution time of the fader queue;. dequeue executes the fader queue.
The last. animate is implemented by default, so you don't need to worry about it. Let's take a look at the effect. The right side is correct, and the right side is wrong (there may be layout misplacement in IE6, because it is a jQuery example and time is limited, I will not pursue css errors ......) :
Truefalse
Complete code in this example:
function animateR(){$("#section4object").delay(1000, "fader").queue("fader", function(next) {$(this).animate({opacity: 0},{duration: 1000, queue: false});next();}).dequeue("fader").animate({top: "-=40"}, {duration: 2000})}function animateU(){$("#section4object2").animate({opacity: 0, top: "-=40"}, {duration: 2000});}$("#section4start").click(function(){$("#section4object,#section4object2").css({'top':'100px','opacity': '1'}).show();animateR();animateU();});
Okay. Here we will introduce the main functions of queue. Here is some time to introduce some non-mainstream functions:
Get Queue Length
For example, use the queue name to get the length of the matching element:
var $queue=$("div").queue('fx');
Obviously, it is to get the queue named 'fx '. If you want to get the length:
var $length=$('div').queue('fx').length;
Note that the queue length here is only the queue length of the matching element that has not been run. After the animation is run, the queue length is automatically classified as 0. For example:
Function animateT () {$ ("# section2-div "). slideToggle ('123 '). slideToggle ('123 '). hide ('20140901 '). show ('20140901 '). animate ({left: '+ = 200'}, 2000 ). hide ('20140901 '). show ('20140901 '). animate ({left: '-= 808080'}, 200, animateT); // call yourself at the end of the animation to make the animation go through infinite loops}
Then, the queue length is displayed when you click the button:
$("#section2-input").click(function(){var $queue=$("#section2-div").queue('fx');$('#section2-h1').text($queue.length);});
Effect:
0
Click the button to view the length of the real-time queue.
Source code for this example:
function animatelength(){$("#section2-div").slideToggle('3000').slideToggle('3000').hide('3000').show('3000').animate({left:'+=200'},2000).hide('3000').show('3000').animate({left:'-=200'},2000,animatelength);}$("#section2-input").click(function(){var $queue=$("#section2-div").queue('fx');$('#section2-h1').text($queue.length);});
animatelength();
Replacement queue
Another use of queue is to replace a queue, that is, after a queue is customized, replace the original matching queue with a custom queue:
For example, you have defined two queues for an element:
$ ('Div '). queue ('fx ', function () {$ ('div '). slideDown ('low '). slideUp ('low '). animate ({left: '+ = 100'}, 4000) ;}); // define fx $ ('div '). queue ('fx2 ', function () {$ ('div '). slideDown ('fast '). slideUp ('fast '). animate ({left: '+ = 100'}, 1000) ;}); // define fx2
Two queues are defined here. One is the slow queue, that is, the default 'fx ', and the other is the fast queue 'fx2'
When you click a button:
$('input').click(function(){ $('div').queue('fx',fx2);});
It's easy. Obviously, fx2 is used to replace fx. Of course, this is not an immediate replacement, If fx is not completed yet. Unless you use the stop () function ).
Summary
OK. Here is the explanation of queue today. There must be a lot of omissions. I hope you will give us a lot of evidence. I have summarized the above usage. It should be a mainstream usage. If you have any questions or want to contact me, leave a message.
Reference materials include jQuery official documentation, Cameron McKay's blog, and cutting-edge jQuery
In the next lesson, I plan to introduce the stop () function, which is also the place where I have followed suit.