让div在屏幕上移动 [英] make a div move across the screen

查看:109
本文介绍了让div在屏幕上移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将彩色div水平移动到右边,当它撞到边缘时,它的尺寸应该加倍,并且围绕中心旋转的速度是两倍。

I need to make a colored div move horizontally to the right and when it hits the edge it should double in size and twice the speed rotating around the center.

var topPosition = 50;
var leftPosition = 250;
var rightPosition = 800;
  function move(){
  var go = document.getElementById("box");
  go.style.left = leftPosition + "px";  
  go.style.right = rightPosition + "px";
  go.style.visibility = "visible";
  ++leftPosition;

  if (leftPosition == 800){
--leftPosition;

它停在800 px,就像我告诉它但它不会回去

it stops at 800 px like I told it but it wont go back

推荐答案

让我们清理一下代码并实现你想要的。按顺序:

Let's clean the code up a bit and implement what you want. In order:


  1. 移至800px

  2. 当1完成后,返回,快两倍,并且尺寸加倍。

我们将使用一个范围变量执行此操作: speed speed 将是默认的速度和方向。

We'll do this using one scoped variable: speed. speed will be the default speed and direction.

我还在中分隔了你的代码setInterval 为了不阻止页面的执行。

I have also separated your code in setInterval in order to not block execution of the page.

function move() {
    var elem = document.getElementById("box"),
        speed = 1,
        currentPos = 0;
    // Reset the element
    elem.style.left = 0+"px";
    elem.style.right = "auto";
    var motionInterval = setInterval(function() {
        currentPos += speed;
        if (currentPos >= 800 && speed > 0) {
           currentPos = 800;
           speed = -2 * speed;
           elem.style.width = parseInt(elem.style.width)*2+"px";
           elem.style.height = parseInt(elem.style.height)*2+"px";
        }
        if (currentPos <= 0 && speed < 0) {
           clearInterval(motionInterval);
        }
        elem.style.left = currentPos+"px";
    },20);
}

小提琴: http://tinker.io/7d393 。你会看到,它有效。

Fiddle: http://tinker.io/7d393 . You'll see, it works.

这篇关于让div在屏幕上移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆