- // 匀速动画
- function animate(obj, target) {
- clearInterval(obj.tim)
- var newvalue = 0;
- obj.tim = setInterval(function () {
- newvalue = obj.offsetLeft + 5;
- if (newvalue >= target) {
- newvalue=target;
- clearInterval(obj.tim)
- }
- obj.style.left = newvalue + 'px';
- }, 30)
-
- }
- // 缓动动画 :(目标值-现在位置)/10
- function animate2(obj, target ,callback) {
- console.log('开始');
- clearInterval(obj.tim)
- var newvalue = 0;
- var step = 0;
- obj.tim = setInterval(function () {
- step =(target - obj.offsetLeft) / 10;
- step =step>0?Math.ceil(step):Math.floor(step);
-
- newvalue = obj.offsetLeft + step;
- if (newvalue >= target&&step>0||newvalue <= target&&step<0) {
- newvalue=target;
- clearInterval(obj.tim);
- if(callback){
- callback()
- }
- console.log('结束');
- }
- obj.style.left = newvalue + 'px';
- }, 30)
- }
动画函数的使用
- html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Documenttitle>
- <style>
- .sliderbar{
- width: 150px;
- height: 50px;
- /* background-color: aqua; */
- position: relative;
- overflow: hidden;
- margin-left: 500px;
- }
- .con{
- width: 50px;
- height: 50px;
- position: absolute;
- background-color: plum;
- top: 0;
- right: 0;
- font-size: 20px;
- line-height: 25px;
- text-align: center;
- }
- span{
- position: absolute;
- height: 50px;
- width: 100px;
- background-color: powderblue;
- top: 0;
- left: 100px;
- line-height: 50px;
- font-size: 20px;
- }
- style>
- head>
- <body>
- <div class="sliderbar">
- <span><span>
- <div class="con">问题反馈div>
- div>
- <script src="./animation.js">script>
- <script>
- var span=document.querySelector('span');
- var con=document.querySelector('.con');
- con.onmouseenter=function(){
- animate2(span,0)
- }
- con.onmouseleave=function(){
- var target=con.offsetLeft;
- animate2(span,target)
- }
-
- script>
- body>
- html>