How can I use jQuery to move a div across the screen

前端 未结 5 1301
旧时难觅i
旧时难觅i 2020-12-30 23:50

I need to make multiple divs move from right to left across the screen and stop when it gets to the edge. I have been playing with jQuery lately, and it seem like what I wa

相关标签:
5条回答
  • 2020-12-30 23:55

    Just a quick little function I drummed up that moves DIVs from their current spot to a target spot, one pixel step at a time. I tried to comment as best as I could, but the part you're interested in, is in example 1 and example 2, right after [$(function() { // jquery document.ready]. Put your bounds checking code there, and then exit the interval if conditions are met. Requires jQuery.

    First the Demo: http://jsfiddle.net/pnYWY/

    First the 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>
    

    example 1) Start

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

    example 2) Delayed Start

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

    Now the Function:

    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)
    
    0 讨论(0)
  • 2020-12-31 00:12

    You will want to check out the jQuery animate() feature. The standard way of doing this is positioning an element absolutely and then animating the "left" or "right" CSS property. An equally popular way is to increase/decrease the left or right margin.

    Now, having said this, you need to be aware of severe performance loss for any type of animation that lasts longer than a second or two. Javascript was simply not meant to handle long, sustained, slow animations. This has to do with the way the DOM element is redrawn and recalculated for each "frame" of the animation. If you're doing a page-width animation that lasts more than a couple seconds, expect to see your processor spike by 50% or more. If you're on IE6, prepare to see your computer spontaneously combust into a flaming ball of browser incompetence.

    To read up on this, check out this thread (from my very first Stackoverflow post no less)!

    Here's a link to the jQuery docs for the animate() feature: http://docs.jquery.com/Effects/animate

    0 讨论(0)
  • 2020-12-31 00:12

    In jQuery 1.2 and newer you no longer have to position the element absolutely; you can use normal relative positioning and use += or -= to add to or subtract from properties, e.g.

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

    And to echo the guy who answered first's advice: Javascript is not performant. Don't overuse animations, or expect things than run nice and fast on your high performance PC on Chrome to look good on a bog-standard PC running IE. Test it, and make sure it degrades well!

    0 讨论(0)
  • 2020-12-31 00:15

    Here i have done complete bins for above query. below is demo link, i think it may help you

    Demo: 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');
                }
    
            });
        });
    });
    

    Demo: http://codebins.com/bin/4ldqp9b/1

    0 讨论(0)
  • Use 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;
    }
    

    script

    var b = function($b,speed){
    
    
        $b.animate({
            "left": "50%"
        }, speed);
    };
    
    $(function(){
        b($("#b"), 5000);
    });
    

    see jsfiddle http://jsfiddle.net/vishnurajv/Q4Jsh/

    0 讨论(0)
提交回复
热议问题