垂直居中有没有更好的方法(怎么用table-cell,用了有一系列问题。。)。为什么t要先置空,赋setInterval给t时,前面用var t就不动了。

来源:3-1 JS缓冲动画

尘埃深蓝

2016-07-14 21:16

<style type="text/css">

*{margin:0;padding:0;}

#box1{width:200px;height:300px;background:#CCF; position:relative;left:-200px;top:100px;border-bottom-right-radius:10px; border-top-right-radius:10px;}

#box2{width:40px;height:100px;background:#F00;text-align:center;border-bottom-right-radius:10px; border-top-right-radius:10px; color:#FFF; font-weight:900; position:absolute;left:200px;top:100px;}

#a{padding-top:32px;}

</style>


</head>


<body>

<div id="box1">

<div id="box2">

<div id="a"><p>分</p>

<p>享</p></div>

</div>

</div>

<script type="text/javascript">

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

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

var t=null;

box1.onmouseover=move;

function move(){

clearInterval(t);

t=setInterval(function(){

if(box1.offsetLeft==0){clearInterval(t);}

else { speed=(0-box1.offsetLeft)/20;

box1.style.left=box1.offsetLeft+Math.ceil(speed)+"px";}

},30);

}

box1.onmouseout=move1;

function move1(){

clearInterval(t);

t=setInterval(function(){

if(box1.offsetLeft==-200){clearInterval(t);}

else { speed=(-200-box1.offsetLeft)/20;

box1.style.left=box1.offsetLeft+Math.floor(speed)+"px";}

},30);

}

</script>

</body>


写回答 关注

1回答

  • 代小代
    2016-07-14 22:19:04

    得用js取到屏幕的clientHeight,然后取到元素的offsetHeight,位置为top=(clientWidth-offsetHeight)/2 表示居中位置,t表示全局变量,就一个定时器在工作吧

JS动画效果

通过本课程JS动画的学习,从简单动画开始,逐步深入各种动画框架封装

113920 学习 · 1500 问题

查看课程

相似问题