js原生動畫一勻速動畫

<!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>
相關文章
相關標籤/搜索