第41天:匀速、缓动运动和图片无缝滚动
一、匀速运动和缓动运动
缓动运动
公式:leader=leader+(target-leader)/10;//leader为初始值0,target为结束值,10可以改变,值越大,速度越慢
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>运动</title> 6 <style> 7 .box{ 8 width: 200px; 9 height: 200px; 10 background-color: yellow; 11 position: absolute; 12 top:100px; 13 left:0; 14 } 15 </style> 16 </head> 17 <body> 18 <button id="btn">开始</button> 19 <div class="box" id="Box"></div> 20 </body> 21 <script> 22 var btn=document.getElementById("btn"); 23 var box=document.getElementById("Box"); 24 //匀速运动 25 /* var timer=null; 26 var num=0; 27 btn.onclick=function(){ 28 timer=setInterval(function(){ 29 num++; 30 if(num>500){ 31 clearInterval(timer); 32 }else{ 33 box.style.left=num+"px"; 34 } 35 36 },10); 37 }*/ 38 39 // 缓动运动 40 var leader=0; 41 var target=500; 42 btn.onclick=function(){ 43 setInterval(function(){ 44 leader=leader+(target-leader)/10;//速度逐渐变慢 45 box.style.left=leader+"px"; 46 },10) 47 } 48 </script> 49 </html>
二、图片无缝滚动
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>图片无缝滚动</title> 6 <style> 7 *{ 8 margin: 0; 9 padding: 0; 10 } 11 ul{ 12 list-style: none; 13 } 14 img{ 15 vertical-align: top; 16 } 17 18 .box{ 19 width: 600px; 20 height: 200px; 21 background-color: pink; 22 margin:100px auto; 23 position: relative; 24 overflow: hidden; 25 } 26 .box ul{ 27 width: 400%; 28 position: absolute; 29 left: 0; 30 top:0; 31 } 32 .box ul li{ 33 34 float: left; 35 } 36 </style> 37 </head> 38 <body> 39 <div class="box" id="scroll"> 40 <ul > 41 <li><img src="images/01.jpg" alt=""></li> 42 <li><img src="images/02.jpg" alt=""></li> 43 <li><img src="images/03.jpg" alt=""></li> 44 <li><img src="images/04.jpg" alt=""></li> 45 <li><img src="images/01.jpg" alt=""></li> 46 <li><img src="images/02.jpg" alt=""></li> 47 </ul> 48 </div> 49 </body> 50 <script> 51 var scroll=document.getElementById("scroll");//大盒子 52 var ul=scroll.children[0]; 53 var num=0;//控制左侧的值 left 54 var timer=null;//存定时器 55 timer=setInterval(autoPlay,5); 56 function autoPlay(){ 57 num--; 58 num<=-1200?num=0:num; 59 ul.style.left=num+"px"; 60 } 61 62 scroll.onmouseover=function(){//鼠标经过大盒子 停止滚动 63 clearInterval(timer); 64 } 65 scroll.onmouseout=function(){ 66 timer=setInterval(autoPlay,5);//鼠标离开 开始滚动 67 68 } 69 </script> 70 </html>
运行效果: