问答详情
源自:2-1 JS速度动画

为什么我的offsetLeft每次加9px

<!doctype>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

<title>透明度动画</title>

<style type="text/css">

#wrap{width:230px;height:105px;position: relative;left:-217px;}

#red{width:200px;height:100px;background-color: red;position: absolute;}

#blue{width:30px;height:30px;background-color: blue;margin-left: 200px;position: absolute;}

</style>

<script type="text/javascript">

window.onload=function(){

var wrap=document.getElementById("wrap");

var timer=null

wrap.onmouseover=function(){

startMove();

}

}


function startMove(){

timer=setInterval(function(){ 


if(wrap.offsetLeft==0){

clearInterval(timer);

}

else{


wrap.style.left=wrap.offsetLeft+1+'px'; //console.log(wrap.offsetLeft);

}

},300);

}

</script>

</head>

<body>

<div id="wrap">

<div id="red"></div>

<div id="blue"></div>                                                        

</div>

</body>

</html>

为什么我的offsetLeft每次加9px

提问者:慕标5802213 2016-03-10 20:37

个回答

  • 一点一
    2016-03-10 23:07:48

    因为wrap获取的offsetLeft不是217  而是209

    他把body的margin也算进去了

    修改办法:

    在样式里添加:  *{ padding:0; margin:0}