2009-02-04 136 views

Respuesta

42

Desea verificar la característica jQuery animate(). La forma estándar de hacer esto es posicionar un elemento absolutamente y luego animar la propiedad CSS "izquierda" o "derecha". Una forma igualmente popular es aumentar/disminuir el margen izquierdo o derecho.

Ahora, una vez dicho esto, debe tener en cuenta la pérdida severa de rendimiento para cualquier tipo de animación que dure más de un segundo o dos. JavaScript simplemente no estaba destinado a manejar animaciones largas, sostenidas y lentas. Esto tiene que ver con la forma en que el elemento DOM se vuelve a dibujar y se vuelve a calcular para cada "cuadro" de la animación. Si está realizando una animación de ancho de página que dura más de un par de segundos, espere ver el aumento de su procesador en un 50% o más. Si está en IE6, prepárese para ver su computadora quemar espontáneamente en una bola llameante de incompetencia del navegador.

Para leer sobre esto, consulte this thread (¡desde mi primera publicación de Stackoverflow no menos)!

Aquí hay un enlace a la documentación de jQuery para lo animado() función: http://docs.jquery.com/Effects/animate

+0

Una nota más: Las animaciones concurrentes multiplican el problema de rendimiento. –

+0

Si el div se coloca fijo, un navegador más inteligente no tiene que volver a dibujar todo el árbol DOM. –

+0

Una fijación o absolución no parece importar para FF3 o Safari 3. Si el navegador está redibujando todo el árbol o no, no estoy seguro. De cualquier manera, mi CPU todavía salta más o menos lo mismo. –

12

En jQuery 1.2 y posteriores ya no tiene que posicionar el elemento absolutamente; puede usar el posicionamiento relativo normal y usar + = o - = para agregar o restar propiedades, p. ej.

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

Y para hacer eco del tipo que respondió primero: el Javascript no funciona. No use demasiadas animaciones, o espere cosas que no sea ejecutar rápido y agradable en su PC de alto rendimiento en Chrome para verse bien en una PC con IE estándar. Pruébalo y asegúrate de que se degrada bien.

1

Aquí he hecho contenedores completos para la consulta anterior. A continuación se enlace demo, creo que puede ayudarle a

Demostración: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'); 
      } 

     }); 
    }); 
}); 

Demostración:http://codebins.com/bin/4ldqp9b/1

+0

Parece tener un error en Chrome –

0

Sólo un poco de función rápida Tamborileé hasta que se mueve DIVs de su posición actual a un punto de destino, a un paso de pixel a la vez. Traté de comentar lo mejor que pude, pero la parte que le interesa está en el ejemplo 1 y el ejemplo 2, justo después de [$ (función() {// jquery document.ready]. Ponga los límites a verificar codifique allí y luego salga del intervalo si se cumplen las condiciones. Requiere jQuery.

En primer lugar la demostración : http://jsfiddle.net/pnYWY/

Primero los 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> 

ejemplo 1) Comience

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

ejemplo 2) Inicio demorado

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

Ahora la Función:

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

Uso 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; 
} 

guión

var b = function($b,speed){ 


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

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

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

Cuestiones relacionadas