Javascript - 用于更改元素位置的setInterval

时间:2014-05-10 14:35:14

标签: javascript position setinterval

我试图弄清楚如何在屏幕上移动元素。我不想使用JQuery的animate()方法,因为我需要更精确的控制。这是基本的想法:

http://jsfiddle.net/9RLkJ/

setInterval(function() {
    var e = document.getElementById("aDiv");
    // Increase the top position by 1 pixel
    e.style.top = '+1px';
    // If the top position is greater than 100px, set it to 100px
    if (parseInt(e.style.top) > 100) { e.style.top = '100px'; }
}, 1000);

谢谢。

2 个答案:

答案 0 :(得分:0)

var top= document.getElementById("aDiv").style.top; setInterval(function() { top += 1; var e = document.getElementById("aDiv"); // Increase the top position by 1 pixel e.style.top = top + 'px'; // If the top position is greater than 100px, set it to 100px if (parseInt(e.style.top) > 100) { e.style.top = '100px'; } }, 1000);

答案 1 :(得分:0)

var e = document.getElementById("aDiv");
var s = 1;
setInterval(function(){
    var eLeftPos = e.offsetLeft;
    e.style.left = (eLeftPos + s) + 'px';

}, 1000);

上面的代码会将框移到右边;

工作演示move the box to bottom