如何按像素移动DIV像素
我有这样的DIV设置。如何按像素移动DIV像素
<div id="parent" class="parent">
<div id="child" class="child">
</div>
</div>
样式
<style>
.parent{
float:left; height:300; width:300px; background-color:#00ff00;
}
.child{
float:left; height:60; width:60px; background-color:#00ff00;
}
</style>
<script>
function move(){
while(m < 100){
document.getElementByid('child').style.marginTop = m;
m = m+1;
}
}
move();
</script>
我想通过像素从顶部100个像素移动内部DIV(名为子)像素底部。 我认为它可以使用style.marginTop =“”和的setTimeout()函数
但依然没能得到这个工作完成。
这里是你如何动画与香草的JavaScript您的DIV:http://jsfiddle.net/z6F7m/1/
的JavaScript
var elem = document.getElementById('animated'),
top = parseInt(elem.style.marginTop, 10) || 0,
step = 1;
function animate() {
if (top < 100) {
requestAnimationFrame(animate);
elem.style.marginTop = top + 'px';
top += step;
}
}
animate();
我强烈建议你使用代替setTimeout
,如果浏览器不支持你可以回退到setTimeout
。这样做的
保罗爱尔兰垫片可能也值得包括:http://paulirish.com/2011/requestanimationframe-for-smart-animating/ – thesonglessbird 2013-03-01 16:46:36
试试这个
var element = document.getElementById('child');
for (var i=0; i != 100; i++){
element.style.marginTop += 1;
}
那将循环100次,加1到marginTop每个循环。
我建议使用jQuery这样想,因为使用jQuery,你可以简单地做
$("#child").animate({ marginTop: 100 });
编辑
顶端示例没有意义,试试这个。
var element = document.getElementById('animated');
for (var i = 0; i != 100; i++) {
currentTop = parseInt(element.style.marginTop) || 0;
newTop = parseInt(currentTop + 1);
element.style.marginTop = newTop + "px";
}
这也是愚蠢的,因为它循环的方式来快速而由当时的浏览器呈现框,它已经100像素从顶部。 See here
再次,请使用jQuery solution。
如果'marginTop'是''10px'',这不会使它成为'10px11111 ...',我们还会有动画吗? – 2013-03-01 16:48:46
好点,更新! – dotty 2013-03-01 17:01:15
检查以下小提琴。我做了没有jQuery。
var step = 0;
window.setInterval(function(){
var value = (++step)*100;
if (value<300)
document.getElementById("child").style.marginTop=value+"px";
else
step = -1;
},1000);
向我们展示你的JavaScript代码。 – Halcyon 2013-03-01 16:40:25
你是指动画吗? – Dogoku 2013-03-01 16:40:30
@dogoku是动画。 – 2013-03-01 16:41:27