Easing Effect of Javascript (Part 1)

Source: Internet
Author: User


Gentle movement. The learning name is Tween, short for buffered movement. To switch the page content comfortably, use the fade-in and fade-out effects. To make the page elements move naturally, use the easing effect. These two combinations can be used to derive a variety of special effects. Thanks to Flash developers for doing so much research for us, we split them directly and packed them in various menus and albums. Let's start with the simplest things to accelerate and slow down.

Since it is slow, it must involve the following concepts: distance, time and speed. We can imagine that there is A straight line L. vertices A and vertices B are the start and end points of L. There is A point C moving on the straight line L from vertices A to B. The time required is generally unknown, but the speed must be determined. As shown in the figure below, we want to move the green square on the thin sliding belt. The upper-left corner of the slider is equivalent to A, and the upper-right corner is equivalent to B. The upper-left corner of the square is equivalent to point C, and the moving distance is the width difference between the two. Because the moving object has a width, that is to say, point C will never overlap with point B. But an accurate destination (point D for convenience) is necessary and we must calculate it. In acceleration, point C may surpass point D at any time. When point is exceeded, we need to stop this movement and pull point C back to point D.


<! DOCTYPE HTML PUBLIC "-// W3C // DTD HTML 4.0 Transitional // EN"> <HTML> <HEAD> <TITLE> New Document </ TITLE> <META NAME = "Generator" CONTENT = "EditPlus"> < META NAME = "Author" CONTENT = ""> <META NAME = "Keywords" CONTENT = ""> <META NAME = "Description" CONTENT = ""> </ HEAD> <BODY> <STYLE type = text / css> #taxiway {BACKGROUND: # e8e8ff; WIDTH: 800px; HEIGHT: 100px} #move {BACKGROUND: # a9ea00; WIDTH: 100px; HEIGHT: 100px} </ STYLE> <DIV id = taxiway> <DIV id = move onclick = move (this)> </ DIV> </ DIV> <P class = notice display = "text-align: center"> Click to move the green square </ P> <SCRIPT type = text / javascript> var getCoords = function (el ) {var box = el.getBoundingClientRect (), doc = el.ownerDocument, body = doc.body, html = doc.documentElement, clientTop = html.clientTop || body.clientTop || 0, clientLeft = html.clientLeft || body.clientLeft || 0, top = box.top + (self.pageYOffset || html.scrollTop || body.scrollTop) – clientTop, left = box.left + (self.pageXOffset || html.scrollLeft || body. scrollLeft) – clien tLeft return {'top': top, 'left': left};}; var getStyle = function (el, style) {if (! + "v1") {style = style.replace (/-(w) / g , function (all, letter) {return letter.toUpperCase ();}); var value = el.currentStyle [style]; (value == "auto") && (value = "0px"); return value;} else {return document.defaultView.getComputedStyle (el, null) .getPropertyValue (style)}} // Auxiliary function 3, equivalent to $ (), naming without the $ symbol is because the blog park is using JQuery, which will cause naming conflicts // I A new generation of method to search for elements, with cache capability var cache = [] var _ = function (id) {return cache [id] || (cache [id] = document.getElementById (id));} var move = function (el) {el.style.position = "absolute"; var begin = getCoords (el) .left, distance = parseFloat (getStyle (_ ("taxiway"), "width")) – parseFloat (getStyle (el, " width ")), end = begin + distance, speed = 10, // The speed of the first move, in px / ms, implicitly multiplied by 1ms delta = 1.5, change = true; el.onclick = function () {if (change) {el.innerHTML = "Accelerate"; (function () {setTimeout (function () {el.style.left = getCoords (el) .left + speed + "px"; // Move speed * = delta; // The distance of the next move if (getCoords (el ) .left> = end) {el.style.left = end + "px"; change = false; delta = 0.85, speed = 100;} else {setTimeout (arguments.callee, 25); // every stay 25 ms}}, 25)}) ()} else {el.innerHTML = "Slowdown"; (function () {setTimeout (function () {el.style.left = getCoords (el) .left – speed + "px "; // Move speed = Math.ceil (speed * delta); // The distance of next move if (getCoords (el) .left <= begin) {el.style.left = begin +" px "; change = true; delta = 1.5, speed = 10;} else {setTimeout (arguments.callee, 25);}}, 25)}) ()}}} window.onload = function () {move (_ ("move") )} </ SCRIPT> </ BODY> </ HTML>

 

Tip: the code can be modified before running!


To obtain the coordinates and dimensions of the pages, getCoords () and getStyle () are now available. Sorry, I really don't mean to show off my functions. What's more, getStyle () has been hacked into many things, and its power is not as powerful as before.


Reference content is as follows:
Var getCoords = function (el ){
Var box = el. getBoundingClientRect (),
Doc = el. ownerDocument,
Body = doc. body,
Html = doc.doc umentElement,
ClientTop = html. clientTop | body. clientTop | 0,
ClientLeft = html. clientLeft | body. clientLeft | 0,
Top = box. top + (self. pageYOffset | html. scrollTop | body. scrollTop)-clientTop,
Left = box. left + (self. pageXOffset | html. scrollLeft | body. scrollLeft)-clientLeft
Return {'top': top, 'left': left };
};

Var getStyle = function (el, style ){
If (! + "\ V1 "){
Style = style. replace (/\-(\ w)/g, function (all, letter ){
Return letter. toUpperCase ();
});
Var value = el. currentStyle [style];
(Value = "auto") & (value = "0px ");
Return value;
} Else {
Return document. defaultView. getComputedStyle (el, null). getPropertyValue (style)
}
}


So how can we move it? In javascript, you only need to change it to an absolute positioning object and assign a value to top and left of the object. It will immediately move to the corresponding coordinates. Because javascript is too efficient in processing location changes, it cannot make you feel "moving". It feels like you directly jump from point C to point D. Every time we move an object a little bit, we have to stop it and let the eyes have a shadow. According to the visual staying effect of human eyes, if the impression left by the previous portrait in the brain has not disappeared, the latter portrait will come one after another, and the difference between the two pictures is very small, there will be a feeling of "motion. So how millisecond is the most suitable? We should not only take care of people's eyes, but also take into account the display speed of the display and the rendering speed of the browser. Based on foreign statistics, 25 ms is the optimal value. In fact, we should remember this value as common sense. In retrospect, there seems to be a rule for Japanese animation that there are 30 pictures in 1 second, which is Chinese, which is relatively junk and 24 screenshots in 1 second. Divide by the number of sheets in one second to get the time of each stay. The 27.77 ms in Japan is very close to our 25 ms, because the rendering speed of the browser is obviously inferior to that of the TV, especially IE6. To achieve acceleration, let it move a little faster each time, and multiply the last moving distance by a number greater than 1.


Reference content is as follows:
// Auxiliary function 3, equivalent to $ (). The $ symbol is not used because JQuery is used in the blog Park, causing Name Conflict.
// My new generation of query Generation Element Method with cache capability
Var cache = []
Var _ = function (id ){
Return cache [id] | (cache [id] = document. getElementById (id ));
}

Var move = function (el ){
El. style. position = "absolute ";
Var begin = getCoords (el). left,
Distance = parseFloat (getStyle (_ ("taxiway"), "width")-parseFloat (getStyle (el, "width ")),
End = begin + distance,
Speed = 10, // The first moving speed, in px/ms, implicitly multiplied by 1 ms
Delta = 1.5,
Change = true;
El. onclick = function (){
If (change ){
El. innerHTML = "acceleration ";
(Function (){
SetTimeout (function (){
El. style. left = getCoords (el). left + speed + "px"; // move
Speed * = delta; // The distance of the next movement
If (getCoords (el). left> = end ){
El. style. left = end + "px ";
Change = false;
Delta = 0.85,
Speed = 100;
} Else {
SetTimeout (arguments. callee, 25); // each move stays for 25 milliseconds
}
}, 25)
}


It is easy to slow down when you understand acceleration. We give the first moving distance a large number, and then reduce each time, in other words, multiply by a number smaller than 1. But here is a note. What if it moves at a distance less than 1px ?! It is also less than 1px later. The browser will ignore this value and treat it as 0. In this way, it will stop in the middle. To prevent such a terrible event, we use Math. ceil to ensure that the minimum moving distance is 1 px, even if the last moving speed is reached.


Reference content is as follows:
// Main function: Slow down and move
Var decelerate = function (el ){
El. style. position = "absolute ";
Var begin = getCoords (el). left,
Distance = parseFloat (getStyle (_ ("taxiway"), "width")-parseFloat (getStyle (el, "width ")),
End = begin + distance,
Speed = 100; // The first moving speed, in px/ms, implicitly multiplied by 1 ms
(Function (){
SetTimeout (function (){
El. style. left = getCoords (el). left + speed + "px"; // move
Speed = Math. ceil (speed * 0.9); // distance of the next movement
If (getCoords (el). left & lt; = end ){
El. style. left = end + "px ";
} Else {
SetTimeout (arguments. callee, 25 );
}
}, 25)
})()
}


At present, functions are still weak, mainly because of the lack of abstraction and formulation. If we overcome these shortcomings and cooperate with the slow-moving formula of Robert Penner, we can achieve a variety of slow effects. This is what we will explain in the next part. We hope you can leave a message for your support.


Related Article

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.