<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>匀速动画</title> <style type="text/css"> html, body { margin: 0; padding: 0; } div { margin: 0; padding: 0; } .father { width: 200px; height: 200px; background: #f00; position: relative; left: -200px; top: 100px; } .son { width: 20px; height: 60px; background: #00f; position: absolute; top: 70px; right: -20px; } </style></head><body><div id="father" class="father"> <div id="son" class="son"> </div></div><script> window.onload = function () { var father = document.getElementById('father'); father.onmouseover = function () { startMover(0); } father.onmouseout = function () { startMover(-200); } } var timer = null; function startMover(itarget) {//目标值 clearInterval(timer);//执行当前动画同时清除以前的动画 var father = document.getElementById('father'); timer = setInterval(function () { var speed = 0; if (father.offsetLeft > itarget) { speed = -1; } else { speed = 1; } if (father.offsetLeft == itarget) { clearInterval(timer); } else { father.style.left = father.offsetLeft + speed + 'px'; } }, 30); } //注明:offsetWidth = width+padding+border //offsetHeight = height+padding+border //offsetWidth=(border-width)*2+(padding-left)+(width)+(padding-right) //offsetHeight=(border-width)*2+(padding-top)+(height)+(padding-bottom) /* offsetLeft=(offsetParent的padding-left)+(中间元素的offsetWidth)+(当前元素的margin-left)。 offsetTop=(offsetParent的padding-top)+(中间元素的offsetHeight)+(当前元素的margin-top)。 当offsetParent为body时状况比较特殊: 在IE8/9/10及Chrome中,offsetLeft = (body的margin-left)+(body的border-width)+(body的padding-left)+(当前元素的margin-left)。 在FireFox中,offsetLeft = (body的margin-left)+(body的padding-left)+(当前元素的margin-left)。 offsetParent属性返回一个对象的引用,这个对象是距离调用offsetParent的元素最近的(在包含层次中最靠近的),而且是已进行过CSS定位的容器元素。 若是这个容器元素未进行CSS定位, 则offsetParent属性的取值为根元素的引用。 总的来讲两条规则: 一、若是当前元素的父级元素没有进行CSS定位(position为absolute或relative),offsetParent为body。 二、若是当前元素的父级元素中有CSS定位(position为absolute或relative),offsetParent取最近的那个父级元素。 */</script></body></html>