2016-03-27 234 views
0

我想每次點擊代碼中指定的類時重複相同的過程。它正在研究懸停功能,但是當我切換到點擊功能時,它只做一次工作。這是不可重複的。切換而不是懸停功能jQuery

此外,我切換到clickToggle,它不起作用。有什麼想法嗎?

var sidebarFloat = $('.sidebar').css('float'); 
$('.sidebar').hover(function() { 
    sidebarFloat = $(this).css('float'); 

    if (sidebarFloat == 'right') { 
     $(this).stop().animate({ 
      left: "0px" 
     }, 500) 
    } else if (sidebarFloat == 'left') { 
     $(this).stop().animate({ 
      left: "0px" 
     }, 500) 
    } 
}, function() { 
    var width = $(this).width() - 10; 
    if (sidebarFloat == 'right') { 
     $(this).stop().animate({ 
      left: +width 
     }, 500); 

    } else if (sidebarFloat == 'left') { 
     $(this).stop().animate({ 
      left: -width 
     }, 500); 
    } 
}); 
+0

也許創造的jsfiddle? –

+0

需要什麼jsfiddle?我已經粘貼了代碼。沒什麼奇特的 – Ahmed

+0

是的,看到我的答案。 –

回答

0

jquery hover()函數有兩個函數作爲參數:handleIn和HandleOut。

Click does not.

因此,你必須追蹤使用單獨的變量點擊的狀態。

例如:

var sidebarFloat = $('.sidebar').css('float'); 
var toggled = false; 
$('.sidebar').click(function() { 
    if (toggled) { 
     sidebarFloat = $(this).css('float'); 
     if (sidebarFloat == 'right') { 
      $(this).stop().animate({ 
       left: "0px" 
      }, 500) 
     } else if (sidebarFloat == 'left') { 
      $(this).stop().animate({ 
       left: "0px" 
      }, 500) 
     } 
    } else { 
     var width = $(this).width() - 10; 
     if (sidebarFloat == 'right') { 
      $(this).stop().animate({ 
       left: +width 
      }, 500); 

     } else if (sidebarFloat == 'left') { 
      $(this).stop().animate({ 
       left: -width 
      }, 500); 
     } 
    } 
    toggled = !toggled; 
}); 
+0

但您仍然擁有懸停功能而不是點擊。 – Ahmed

+0

呃。謝謝。固定。 –

+0

謝謝你,謝謝。 – Ahmed