如何使用jQuery在屏幕上移动div

时间:2009-02-04 04:21:40

标签: javascript jquery

我需要让多个div在屏幕上从右向左移动,并在到达边缘时停止。我最近一直在玩jQuery,看起来我想要的就可以用它来完成。有没有人知道我在哪里可以找到这样的例子?

5 个答案:

答案 0 :(得分:42)

您需要查看jQuery animate()功能。执行此操作的标准方法是绝对定位元素,然后设置“左”或“右”CSS属性的动画。同样流行的方法是增加/减少左边距或右边距。

现在,说到这一点,您需要注意任何类型的动画持续时间超过一两秒的严重性能损失。 Javascript根本不是为了处理长,持续,慢的动画。这与为动画的每个“帧”重绘和重新计算DOM元素的方式有关。如果你正在做一个持续时间超过几秒的页面宽度动画,那么预计处理器的峰值会增加50%或更多。如果您使用的是IE6,请准备好让您的计算机自发地燃烧成浏览器无能的火焰球。

要阅读此内容,请查看this thread(从我的第一篇Stackoverflow帖子开始)!

以下是animate()功能的jQuery文档的链接:http://docs.jquery.com/Effects/animate

答案 1 :(得分:12)

在jQuery 1.2及更新版本中,您不再需要绝对定位元素;您可以使用常规相对定位并使用+ =或 - =来添加或减去属性,例如

$("#startAnimation").click(function(){
    $(".toBeAnimated").animate({ 
        marginLeft: "+=250px",
    }, 1000 );
});

回应那个回答第一个建议的人:Javascript不具备表现力。不要过度使用动画,或者期望在Chrome上的高性能PC上运行良好而快速的东西,以便在运行IE的沼泽标准PC上看起来不错。测试它,并确保它降级良好!

答案 2 :(得分:2)

使用jQuery

HTML

<div id="b">&nbsp;</div>

CSS

div#b {
    position: fixed;
    top:40px;
    left:0;
    width: 40px;
    height: 40px;
    background: url(http://www.wiredforwords.com/IMAGES/FlyingBee.gif) 0 0 no-repeat;
}

脚本

var b = function($b,speed){


    $b.animate({
        "left": "50%"
    }, speed);
};

$(function(){
    b($("#b"), 5000);
});

请参阅jsfiddle http://jsfiddle.net/vishnurajv/Q4Jsh/

答案 3 :(得分:1)

这里我已经为上面的查询完成了完整的垃圾箱。下面是演示链接,我想它可以帮到你

演示: http://codebins.com/bin/4ldqp9b/1

<强> HTML:

<div id="edge">
  <div class="box" style="top:20; background:#f8a2a4;">
  </div>
  <div class="box" style="top:70; background:#a2f8a4;">
  </div>
  <div class="box" style="top:120; background:#5599fd;">
  </div>
</div>
<br/>
<input type="button" id="btnAnimate" name="btnAnimate" value="Animate" />

<强> CSS:

body{
  background:#ffffef;
}
#edge{
  width:500px;
  height:200px;
  border:1px solid #3377af;
  padding:5px;
}

.box{
  position:absolute;
  left:10;
  width:40px;
  height:40px;
  border:1px solid #a82244;
}

<强> JQuery的:

$(function() {
    $("#btnAnimate").click(function() {
        var move = "";
        if ($(".box:eq(0)").css('left') == "10px") {
            move = "+=" + ($("#edge").width() - 35);
        } else {
            move = "-=" + ($("#edge").width() - 35);
        }
        $(".box").animate({
            left: move
        }, 500, function() {
            if ($(".box:eq(0)").css('left') == "475px") {
                $(this).css('background', '#afa799');
            } else {
                $(".box:eq(0)").css('background', '#f8a2a4');
                $(".box:eq(1)").css('background', '#a2f8a4');
                $(".box:eq(2)").css('background', '#5599fd');
            }

        });
    });
});

演示: http://codebins.com/bin/4ldqp9b/1

答案 4 :(得分:0)

我只是一个快速的小功能,它将DIV从当前位置移动到目标点,一次一个像素步。我试图尽可能地评论,但你感兴趣的部分是示例1和示例2,紧跟在[$(function(){ // jquery document.ready ]之后将你的边界检查代码放在那里,然后在条件满足时退出间隔。需要jQuery。

首先演示http://jsfiddle.net/pnYWY/

首先是DIV ......

<style>
  .moveDiv {
    position:absolute;
    left:20px;
    top:20px;
    width:10px;
    height:10px;
    background-color:#ccc;
  }

  .moveDivB {
    position:absolute;
    left:20px;
    top:20px;
    width:10px;
    height:10px;
    background-color:#ccc;
  }
</style>


<div class="moveDiv"></div>
<div class="moveDivB"></div>

示例1)开始

// first animation (fire right away)
var myVar = setInterval(function(){
    $(function() { // jquery document.ready

        // returns true if it just took a step
        // returns false if the div has arrived
        if( !move_div_step(55,25,'.moveDiv') )
        {
            // arrived...
            console.log('arrived'); 
            clearInterval(myVar);
        }

    });
},50); // set speed here in ms for your delay

示例2)延迟启动

// pause and then fire an animation..
setTimeout(function(){
    var myVarB = setInterval(function(){
        $(function() { // jquery document.ready
            // returns true if it just took a step
            // returns false if the div has arrived
            if( !move_div_step(25,55,'.moveDivB') )
            {
                // arrived...
                console.log('arrived'); 
                clearInterval(myVarB);
            }
        });
    },50); // set speed here in ms for your delay
},5000);// set speed here for delay before firing

现在功能:

function move_div_step(xx,yy,target) // takes one pixel step toward target
{
    // using a line algorithm to move a div one step toward a given coordinate.
    var div_target = $(target);

    // get current x and current y
    var x = div_target.position().left; // offset is relative to document; position() is relative to parent;
    var y = div_target.position().top;

    // if x and y are = to xx and yy (destination), then div has arrived at it's destination.
    if(x == xx && y == yy)
        return false;

    // find the distances travelled
    var dx = xx - x;
    var dy = yy - y;

    // preventing time travel
    if(dx < 0)          dx *= -1;
    if(dy < 0)          dy *= -1;

    // determine speed of pixel travel...
    var sx=1, sy=1;

    if(dx > dy)         sy = dy/dx;
    else if(dy > dx)    sx = dx/dy;

    // find our one...
    if(sx == sy) // both are one..
    {
        if(x <= xx) // are we going forwards?
        {
            x++; y++;
        }
        else  // .. we are going backwards.
        {
            x--; y--;
        }       
    }
    else if(sx > sy) // x is the 1
    {
        if(x <= xx) // are we going forwards..?
            x++;
        else  // or backwards?
            x--;

        y += sy;
    }
    else if(sy > sx) // y is the 1 (eg: for every 1 pixel step in the y dir, we take 0.xxx step in the x
    {
        if(y <= yy) // going forwards?
            y++;
        else  // .. or backwards?
            y--;

        x += sx;
    }

    // move the div
    div_target.css("left", x);
    div_target.css("top",  y);

    return true;
}  // END :: function move_div_step(xx,yy,target)
相关问题