2012-05-23 2 views
2

Я идиот, поэтому вот оно ...Как остановить навигационную кнопку от нажатия до завершения анимации?

Проблема: Я использую навигационную систему типа слайд-шоу для просмотра продуктов. Все хорошо и полезно до тех пор, пока следующие/предыдущие стрелки не будут нажаты несколько раз до окончания анимации. Нажатие на нее более одного раза заставляет вещь полностью заблуждаться и посылает divs в необратимую горизонтальную спираль через Ад. Мне было интересно, есть ли способ, чтобы пользователь не нажимал на следующие/предыдущие стрелки более одного раза, чтобы навигация слайд-шоу не удалялась.

Код:

var SlideWidth = 305; 
    var SlideSpeed = 1000; 

    $(document).ready(function() { 
     // set the prev and next buttons display 
     SetNavigationDisplay(); 
    }); 

    function CurrentMargin() { 
     // get current margin of slider 
     var currentMargin = $("#slider-wrapper").css("margin-left"); 

     // first page load, margin will be auto, we need to change this to 0 
     if (currentMargin == "auto") { 
      currentMargin = 0; 
     } 

     // return the current margin to the function as an integer 
     return parseInt(currentMargin); 
    } 

    function SetNavigationDisplay() { 
     // get current margin 
     var currentMargin = CurrentMargin(); 

     // if current margin is at 0, then we are at the beginning, hide previous 
     if (currentMargin == 0) { 
      $("#PreviousButton").hide(); 
     } 
     else { 
      $("#PreviousButton").show(); 
     } 

     // get wrapper width 
     var wrapperWidth = $("#slider-wrapper").width(); 

     // turn current margin into postive number and calculate if we are at last slide, if so, hide next button 
     if ((currentMargin * -1) == (wrapperWidth - SlideWidth)) { 
      $("#NextButton").hide(); 
     } 
     else { 
      $("#NextButton").show(); 
     } 
    } 

    function NextSlide() { 
     // get the current margin and subtract the slide width 
     var newMargin = CurrentMargin() - SlideWidth; 

     // slide the wrapper to the left to show the next panel at the set speed. Then set the nav display on completion of animation. 
     $("#slider-wrapper").animate({ marginLeft: newMargin }, SlideSpeed, 'easeInOutElastic', function() { SetNavigationDisplay() }); 

} 

    function PreviousSlide() { 
     // get the current margin and subtract the slide width 
     var newMargin = CurrentMargin() + SlideWidth; 

     // slide the wrapper to the right to show the previous panel at the set speed. Then set the nav display on completion of animation. 
     $("#slider-wrapper").animate({ marginLeft: newMargin }, SlideSpeed, 'easeOutElastic', function() { SetNavigationDisplay() }); 
    } 

И кнопки навигации:

<a href="javascript:void(0)" onclick="PreviousSlide()" id="PreviousButton" style="padding-right:40px;"><img src="IMGS/arrow2.png"></a><a href="javascript:void(0)" onclick="NextSlide()" id="NextButton" style="padding-right:40px;"><img src="IMGS/arrow.png"></a> 

Любая помощь = секс поклонение от меня.

Спасибо!

ответ

1

Установите флаг animating, который вы установили на true, когда начинается анимация, и false в функции обратного вызова конца анимации. Затем просто проверьте состояние флага, чтобы определить, запускаете ли вы следующую/предыдущую логику.

var animating = false; 

// ...SNIP... 

    function NextSlide() { 
     if (!animating) { 
      animating = true; 

      // get the current margin and subtract the slide width 
      var newMargin = CurrentMargin() - SlideWidth; 

      // slide the wrapper to the left to show the next panel at the set speed. Then set the nav display on completion of animation. 
      $("#slider-wrapper").animate({ marginLeft: newMargin }, SlideSpeed, 'easeInOutElastic', function() { animating = false; SetNavigationDisplay() }); 
     } 
    } 

    function PreviousSlide() { 
     if (!animating) { 
      animating = true; 

      // get the current margin and subtract the slide width 
      var newMargin = CurrentMargin() + SlideWidth; 

      // slide the wrapper to the right to show the previous panel at the set speed. Then set the nav display on completion of animation. 
      $("#slider-wrapper").animate({ marginLeft: newMargin }, SlideSpeed, 'easeOutElastic', function() { animating = false; SetNavigationDisplay() }); 
     } 
    } 
+0

Мой бог. Ты гений. Работал как шарм !! Застрял на этом в течение двух дней! ALL HAIL THE MIGHTY mVChr !!!! –

0

имеют переменную определенную как var animationFinished = "no"; и один раз в комплекте, пусть это будет animationFinished = yes;. Затем выполните условное высказывание if (animationFinished == "yes"), как только процесс клика будет выполнен.

Это лучше сделать это логическая переменная, так что это bool animationFinished = false; или true

Или правильный способ сделать это.

$("#PreviousButton").click({ 
    $("#PreviousButton").fadeOut(300); 
    $("#slider-wrapper").animate({ 
     marginLeft: newMargin }, SlideSpeed, 'easeInOutElastic', 
    ), 5000, function() { 
     // Animation complete. 
     SetNavigationDisplay(); 
     $("#PreviousButton").fadeIn(300); 
     }; 
}); 

Лучший способ сделать это, чтобы использовать функцию .addClass и .removeClass, и имеют для этого условными.

jQuery Я не думаю, что есть функция, чтобы проверить, завершена ли каждая анимация. Вам просто нужно использовать обратный вызов, который имеет функция .animate, тем, что находится внутри последующих скобок function(){ }.

Смежные вопросы