js中的运动
缓慢隐藏与出现
效果:
鼠标移至分享上黄色区域自动向左隐藏。
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> div{ background-color: yellow; height: 200px; width: 150px; position: absolute; top:50px; left: -150px; } span{ background-color: red; position: absolute; top:80px; left: 150px; } </style> <script type="text/javascript"> window.onload = function(){ var oDiv = document.getElementsByTagName('div')[0]; oDiv.onmouseout = function(){ startMove(-150); } oDiv.onmouseover = function(){ startMove(0); } } var timer = null; function startMove(target){ var oDiv = document.getElementsByTagName('div')[0]; var speed = 10; if(oDiv.offsetLeft>target) speed = -10; //防止定时器被多次调用 clearInterval(timer); timer = setInterval(function(){ if(oDiv.offsetLeft != target){ oDiv.style.left = oDiv.offsetLeft+speed+'px'; } else clearInterval(timer); }, 30); } </script> </head> <body> <div><span>分享</span></div> </body> </html>
使用绝对定位,通过获取offsetLeft(相对于浏览器左边框的距离)的值和left来确定黄色区域的位置
图像透明度渐变效果
当鼠标移入图像时颜色变亮,移除时颜色变暗
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> div{ background-color: yellow; height: 200px; width: 150px; filter:alpha(opacity:30); opacity: 0.3; } </style> <script type="text/javascript"> window.onload = function(){ var oDiv = document.getElementsByTagName('div')[0]; oDiv.onmouseout = function(){ startMove(30); } oDiv.onmouseover = function(){ startMove(100); } } var timer = null; var alpha = 30; function startMove(target){ var oDiv = document.getElementsByTagName('div')[0]; var speed = 10; //防止定时器被多次调用 if(alpha > target) speed = -10; clearInterval(timer); timer = setInterval(function(){ if(alpha != target){ alpha += speed; oDiv.style.filter = "alpha(opacity:"+alpha+")"; oDiv.style.opacity = alpha/100; } else clearInterval(timer); }, 30); } </script> </head> <body> <div></div> </body> </html>