2012-02-25 2 views
8

div를 특정 영역 내에서 앞뒤로 수평으로 움직이기를 원합니다. 지금 당장 가지고있는 문제는 그것이 앞으로 나아간 후에 어떻게 나의 div 이동을 되돌릴 수 있는지 알 수 없다는 것입니다.jquery의 애니메이션 방법을 사용하여 div를 앞뒤로 움직이게하는 방법

<script type="text/javascript"> 
    var animatethis = function (targetElement, speed) { 
     $(targetElement).animate(
      { 
       marginLeft: "+=250px" 
      }, 
      { 
       duration: speed, 
       complete: function() { 
        animatethis(this, speed); 
        animatethis.stop(); 
        $(targetElement).animate({ marginLeft: "-=250px" }); 
       } 
      } 
        ) 
    }; 
    animatethis($('#q1'), 5000); 
</script> 
+0

루프를 원하십니까? –

+0

첫 번째 애니메이션 후에 콜백 만하면된다. –

+0

예 이걸 명확하게하지 않으면 미안 해요. – user798774

답변

7

봐 여기

은 내가 사용하고있는 스크립트입니다. animatethis 라인

animatethis.stop(); 

항상 충돌하는 것입니다 즉, 아무것도 반환하지 않습니다 (같은 것을 "형식 오류 : 정의되지 않은 방법 '스톱'을 호출 할 수 없습니다"). complete 콜백에서 애니메이션의 순서를 뒤섞고 있습니다.

숨을 쉬고 위의 코드가 실제로하는 일에 대해 생각해보십시오.


좋아

때문에 marginLeft이 증가 후, 당신은 그것을 감소합니다. 다음에을 다시 시작하고 싶습니다. 권리? 따라서 :

function animatethis(targetElement, speed) { 
    $(targetElement).animate({ marginLeft: "+=250px"}, 
    { 
     duration: speed, 
     complete: function() 
     { 
      targetElement.animate({ marginLeft: "-=250px" }, 
      { 
       duration: speed, 
       complete: function() 
       { 
        animatethis(targetElement, speed); 
       } 
      }); 
     } 
    }); 
}; 

animatethis($('#q1'), 5000); 

이 고양이를 껍질을 벗기는 방법은 많이 있지만 작동하지 않습니다. http://jsfiddle.net/mattball/rKu6Y/

+0

와우 덕분에 필자는 필자가 필요로했던 것을 고맙게 생각했습니다. 출력 패널에 인쇄물을 인쇄하는 것을 멈추었을 때 – user798774

+0

왜 스택 오버 플로우 예외를 유발하지 않는지 궁금합니다. 이것은 본질적으로 무한 재귀입니다. – Neolisk

+1

@Nolisk 콜백은 스택에 계속 추가되지 않고 나중에 호출됩니다. –

0

사용 jQuery를 queue() 방법을 체인 이벤트 : 브라우저 콘솔에서 http://api.jquery.com/queue/

+0

Meh. 도움이되지 않습니다. -1 –

+0

당신이 그것을 중요하게 생각합니다. :) – yoda

7

시도 하시겠습니까? http://jsfiddle.net/vwH6R/2/

setInterval(function(){ 
    $("div").stop(true,true).animate({left: 300}, 1000, 
      function(){ $(this).stop(true,true).animate({left: 0}, 1000); 
    }); 
}, 2000);​ 
+1

이것은 최고입니다. – aleXela

3

시도 this 바이올린

HTML

<div class="myDiv">A Div</div>​ 

JS

$('.myDiv').animate({ 
    'margin-left':'50px' 
}, 500, function(e){ 
$('.myDiv').animate({ 
    'margin-left':'0px' 
}, 500)});​ 
+0

나는 OP가 애니메이션을 반복하고 싶다고 생각한다. 아마 내가 틀렸어. –

+0

고마워요.하지만 전 단지 앞으로 나아가고 다시하고 싶다고 생각했습니다. –

1

당신이 N에 대한 앞뒤로 이동하려는 경우 시간, 당신은 그것을 스스로를 호출하는 함수로 감쌀 수 있습니다. 다음과 같은 것 :

function wobble(selector, amount, times, intSpeed) { 

    var string = String($(selector).css("marginLeft")).replace("px", ""), 
    leftMargin = parseInt(string, 10); 

    $(selector).animate({ marginLeft: (leftMargin + amount) + 'px' }, intSpeed, function() { 
     if (times > 0) { 
      wobble(selector, -amount, --times, intSpeed); 
     } else { 
      $(selector).css("marginLeft", leftMargin + 'px'); 
     } 
    }); 
} 
관련 문제