任意值的运动框架
任务描述:
当鼠标移入“透明度”矩形时,该矩形透明度逐渐增加至不透明,移出该矩形,透明度逐渐恢复至初始值;同时该运动框架可以支持其它属性的变化。
示例图
<!DOCTYPE html> <html> <head lang="zh-CN"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"> <title>任意值运动框架</title> <style> div { width: 200px; height: 200px; margin: 20px; float: left; background: yellow; border: 10px solid black; filter: opacity(alpha=30); opacity: 0.3; } </style> </head> <body> <div id='div1'>变透明度</div> <input type='text' id='input' /> <script type="text/javascript"> //补充代码 </script> </body> </html>
参考代码:
oDiv1 = document.getElementById('div1'); oInput = document.getElementById('input'); oDiv1.onmouseover = function () { startMove(this, 'opacity', 100) } oDiv1.onmouseout = function () { startMove(this, 'opacity', 30) } function getStyle(obj, name) { if (obj.currentStyle) { return obj.currentStyle[name]; } else { return getComputedStyle(obj, null)[name]; } } function startMove(obj, attr, iTarget) { clearInterval(obj.timer); obj.timer = setInterval(function () { var cur = 0; if (attr == 'opacity') { //Math.round()四舍五入取整主要是针对低浮点数的精度问题。 cur = Math.round(parseFloat(getStyle(obj, attr)) * 100); } else { cur = parseInt(getStyle(obj, attr)); } var speed = (iTarget - cur) / 6; speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); if (cur == iTarget) { clearInterval(obj.timer); } else { if (attr == 'opacity') { obj.style.opacity = (cur + speed) / 100; obj.style.filter = 'alpha(opacity=' + (cur + speed) + ")"; oInput.value = obj.style.opacity; } else { obj.style[attr] = cur + speed + 'px'; } } }, 30) }