如何使用jQuery将一个div沿着屏幕移动?

26

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

5个回答

42
您需要了解jQuery animate()特性。标准方法是将元素绝对定位,然后动画化“left”或“right”CSS属性。同样受欢迎的方法是增加/缩小左侧或右侧边距。
但是需要注意,在持续时间超过一两秒钟的任何类型的动画中会出现严重的性能损失。JavaScript并不适合处理长时间、持续、慢速的动画。这与DOM元素在每个动画“帧”中被重新绘制和重新计算有关。如果您正在进行一个宽度为整个页面的动画,并且持续时间超过几秒钟,请预期您的处理器使用率会增加50%或更多。如果您使用的是IE6,请准备看到您的计算机突然成为一个浏览器无能的火球。
要了解更多信息,请查看此线程(来自我的Stackoverflow首篇帖子!):https://stackoverflow.com/questions/459302/cross-browser-jquery-transition-animation/459547#459547 这是animate()功能的jQuery文档链接:http://docs.jquery.com/Effects/animate

另外需要注意的是:并发动画会加剧性能问题。 - Jeremy Ricketts
如果 div 元素被定位为 fixed,则更智能的浏览器无需重新绘制整个 DOM 树。 - Georg Schölly
固定或绝对似乎对FF3或Safari 3都没有影响。无论浏览器是否重新绘制整个树形结构,我都不确定。不管怎样,我的CPU使用率仍然会跳得一样高。 - Jeremy Ricketts
1
哦,天啊!我不知道 JavaScript 动画会有性能问题!感谢提供这些信息。 - lidermin

13

在jQuery 1.2及更高版本中,您不再需要绝对定位元素;您可以使用普通的相对定位并使用“+=”或“-=”来增加或减少属性值,例如:

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

还有要重复一下第一个回答者的建议:JavaScript的性能并不理想。不要过度使用动画效果,也不要期望在高性能电脑上使用Chrome时运行良好的东西,在运行IE的普通电脑上也会表现良好。测试一下,并确保它能够良好降级!


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/

1

这里我已经为上面的查询做好了完整的bins。以下是演示链接,我认为它可能对你有所帮助

演示: 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


0

这是一个关于编程的内容。下面是翻译:

这里有一个快速的小函数,可以一次移动一个像素来将 DIV 从当前位置移动到目标位置。我尽量添加了注释,但你感兴趣的部分是在示例1和示例2中,在 [$(function() {// jquery document.ready] 之后。在那里添加边界检查代码,如果满足条件,则退出计时器。需要使用 jQuery。

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

接下来是 DIVs...

<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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接