我有一个上下动画的 div,效果很好。我遇到的问题是,每次页面加载时,div 从页面的最顶部开始,然后在动画开始后跳到它需要的位置。
<body id="body">
<div id="square"></div>
</body>
#body {
background: #000;
}
#square {
background-color: #fff;
margin: 0 auto;
position: relative;
width: 100px;
height: 100px;
}
var box = document.getElementById('square');
TOP = (window.innerHeight - box.offsetHeight)/2;
box.style.top = TOP;
var down = setInterval(animateDown, 15);
var up;
function animateDown()
{
TOP += 3;
box.style.top = TOP + 'px';
if(TOP > 900){
clearInterval(down);
up = setInterval(animateUp, 15);
}
}
function animateUp()
{
TOP -= 3;
box.style.top = TOP + 'px';
if(TOP <= (window.innerHeight - box.offsetHeight)/2){
clearInterval(up);
down = setInterval(animateDown, 15);
}
}
这里也是 jsfiddle 的链接 >> https://jsfiddle.net/xgilmore/pLbgvc3L/
提前致谢
最佳答案
这是一种解决方法,但您可以在开始时将框设置为隐藏状态,然后在开始设置动画后,将其设置为可见。 https://jsfiddle.net/pLbgvc3L/1/
function animateDown()
{
box.style.visibility = 'visible';
#square {
background-color: #fff;
//margin: 0 auto;
position: relative;
width: 100px;
height: 100px;
top: 20%;
visibility: hidden;
}
哦,抱歉,我其实知道发生了什么,只是看了两眼才弄明白。 top: 20%
不执行任何操作,因为百分比仅在父元素(正文)具有明确高度时才有效。像这样https://jsfiddle.net/pLbgvc3L/2/
关于javascript - 错误位置的动画加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36091212/