使用JS移动元素

时间:2015-09-16 20:58:05

标签: javascript jquery html

我遇到过这个网站: http://uploaded.net/

我非常喜欢他们左右移动文件的方式。 我想知道,如何实现这一目标?

我尝试了什么:

我尝试放置标准的HTML图像并绝对移动位置,虽然它有效但没有实际的方法可以将它们循环回来或使它看起来......合法......而不是hacky。

我可以使用任何建议或插件吗?

1 个答案:

答案 0 :(得分:1)

他们就像你描述的那样做!

enter image description here

实现这一目标的方法有很多种。

阅读这些关于setInterval()和setTimeout()的文章,了解如何在JavaScript中创建循环:

https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout

甚至更好,requestAnimationFrame():

https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame


编辑: 你告诉我问题是回到开始,对吗?

你可以有一个setInterval函数,检查每N毫秒元素的“左”。如果它通过一个点,比如300px,则将其重置为0;

类似的东西:

var icon = document.getElementById("something");
var left = 0;
var speed = 1; // change this according to your taste

//... setup the image, position to absolute, etc...

setInterval(function() {
    left += speed;

    if(left >= 300) {
        left = 0;
    }
    icon.style.left = left + "px";
}, 100); //run every 0.1 seconds

这是一个非常基本的例子,但是......


编辑2:处理多个对象

可以有更好的方法,但我会将所有内容放在一个对象中并创建这些对象的数组,如下所示:

var MAX_LEFT = 300;

function animatedIcon(id) {
    this.left = 0;
    this.opacity = 1;
    this.speed = 3;
    this.element = document.getElementById(id);
}

var icons = [];

for(var i = 1; i <= 20; i++) {
    // suposing you have the ids of your DOM elements like "icon1", "icon2", ...
    icons.push(new animatedIcon("icon"+i));
}

//You may want to tweek specific elements start position, speed or opacity, so icon can start from a different position
icons[2].left = 200;
icons[7].left = 17;
//...

setInterval(function() {
    for(i in icons) {
        icons[i].left += icons[i].speed;
        icons[i].opacity -= 0.01;
    }

    if(icons[i].left >= MAX_LEFT) {
        icons[i].left = 0;
        icons[i].opacity = 1;
    }

    icons[i].element.style.left = icons[i].left + "px";
    icons[i].element.opacity = icons[i].opacity;
}, 1000/60); //a basic "60 frames per second" rate.
相关问题