Home > Article > Web Front-end > How to use JS to implement simple folding and unfolding animation
This time I will show you how to operate JS to implement a simple folding and unfolding animation. What are the precautions for operating JS to implement a simple folding and unfolding animation? The following is a practical case, let's take a look.
<!DOCTYPE = html> <html> <head> <title>JS折叠展开动画</title> <style> body{ margin: 0px; padding: 0px; } .red{ background-color:red; width:200px; height:200px; position:relative; left:-200px; top:0px; } .blue{ background:blue; width:20px; height:50px; position:absolute; left:200px; top:75px; } </style> </head> <body> <p class="red" id="cf1"><p class="blue" id="cf">分享</p></p> <script> window.onload = function(){ var onp = document.getElementById("cf1"); onp.onmouseover = function(){ startmove(0); } onp.onmouseout = function(){ startmove(-200); } } var timer ; function startmove(target){ clearInterval(timer);//清除定时器,以免多次触发定时器导致速度越来越快而不是匀速前进 var onp1 = document.getElementById("cf1"); timer = setInterval(function(){ var speed = 0; if(onp1.offsetLeft<target){ speed = 10; }else{ speed = -10; } if(onp1.offsetLeft==target){ clearInterval(timer); } else{ onp1.style.left = onp1.offsetLeft+speed+'px'; } },30) } </script> </body> </html>Running effect:
Summary:
##1. css part:1. Don’t forget style initialization;
2. Review the reference method of css files; (class reference method)3. Review
Absolute positioning
and relative positioning relationships (parent relationships use relative; child relationships use absolute)
1.
element.style.left& element.offsetLeftDifference: ① The unit of the former is px, which is a string; the unit of the latter is a numerical value;
② For other information, please refer to: http://www.jb51.net/article/43981.htm
2. The idea is not clear enough at first, and the key variables of placing and moving the mouse cannot be abstracted - the target position is just different.
3.
Function parametersAs few as possible (if the goal can be achieved) 4. It is best to set the mouse action object to the parent p, otherwise it will appear Flickering situation (
onmouseoverwas just called, the target was removed, and onmouseout was called again) 5. Pay attention to clearing the timer (①, to prevent unstable speed when moving② , stop moving at the target location)
3. Others:Q: Unblock pop-up windows in Google Chrome?
A: Settings-Advanced Settings-Privacy Settings-Content Settings-Pop-up window to make relevant settings.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How to use DOM nodes in JSHow to use JS to implement buffering movementThe above is the detailed content of How to use JS to implement simple folding and unfolding animation. For more information, please follow other related articles on the PHP Chinese website!