1.html代码
<body> <div id="container"> <span id="btn"></span> </div> </body>
2.css样式
*{ margin: 0; padding: 0; } #container{ height: 200px; 200px; position: relative; left: -200px; background-color: #6effcd; } #btn{ height: 60px; 30px; position: absolute; left: 200px; top: 75px; background-color: #73eeff; }
3.js代码
window.onload = function(){ var container=document.getElementById('container'); var btn=document.getElementById('btn'); //实现透明度动画 btn.onmouseover = function(){ moveStart(10,100); }; btn.onmouseout = function(){ moveStart(-10,30); } //实现匀速移动 btn.onclick = function(){ if(container.offsetLeft==-200) { moveOut(); } else{ moveBack(); } }; }; var timer=null;//控制container匀速移动的timer function moveOut(){ clearInterval(timer); timer=setInterval(function(){ if(container.offsetLeft == 0) { clearInterval(timer); } else{ container.style.left=container.offsetLeft+10+'px'; } },30); } function moveBack(){ clearInterval(timer); timer=setInterval(function(){ if(container.offsetLeft == -200) { clearInterval(timer); } else{ container.style.left=container.offsetLeft-10+'px'; } },30); } var alpha = 50; var timer1=null;//控制btn透明度动画的timer function moveStart(oSpeed,oTarget){ clearInterval(timer1); timer1 = setInterval(function(){ if(oTarget == alpha){ clearInterval(timer1); } else{ alpha += oSpeed; btn.style.filter = 'alpha(opacity:'+alpha+');' btn.style.opacity = alpha/100.0; } },30); }