2016-08-12 55 views
0

我真的在這個問題上苦苦掙扎。jQuery IF不適用於位置相對+百分比值

我試圖創建一個菜單,幻燈片左側和右側隱藏自己,與jquery。

我需要使它left: 100%和上單擊切換,使其left: 0

要做到這一點,我也需要它position relative。但似乎,如果它有position relative,jquery if不起作用。

$('.menu-toggle').click(function(){ 
     if ($('.menu').css('left') == '100%') { 
      alert('left 100%'); 
      $(this).text('keyboard_arrow_right'); 
      $('.menu').stop().animate({ 
       left: 0 
      }, 500); 
     } 
     else { 
      alert('left not 100%'); 
      $(this).text('menu'); 
      $('.menu').stop().animate({ 
       left: '100%' 
      }, 500); 
     } 
}); 

我做了這個小提琴,使其更容易進行測試:https://jsfiddle.net/z2cjLrtq/2/

如果你試圖從小提琴刪除position relative,代碼工作,但隨後,left: 100%不會做的事情,因爲它沒有position relative

我也嘗試使用px而不是%,它也可以工作!但是這對我來說不會有任何好處,因爲它將是一個具有流體寬度的動態菜單。

我開始認爲這是一個jQuery錯誤...

是否有任何解決這個?

我真的很感謝一些幫助。

預先感謝您

+0

[獲取與jQuery%的CSS位置]的可能的複製(http://stackoverflow.com/questions/5230425/getting-percent-css-position-with-jquery) –

回答

1

$('.menu').css('left')返回以像素爲單位的實際(計算值)的值,例如0px879px,而不是100%

因此,所有你需要做的是扭轉你的邏輯,讓你檢查的0px情況下(當菜單在左邊),而不是試圖找出其像素值相當於100%。就像這樣:

$('.menu-toggle').click(function(){ 

     if ($('.menu').css('left') == '0px') { 
      $(this).text('menu'); 
      $('.menu').stop().animate({ 
       left: '100%' 
      }, 500); 
     } 
     else { 
      alert($('.menu').css('left')); 
      $(this).text('keyboard_arrow_right'); 
      $('.menu').stop().animate({ 
       left: 0 
      }, 500); 
     } 
}); 
+1

我沒不知道那個。我的頭痛消失了。你是一個真正的救世主! – White8Tiger

1

一個簡單的解決方案是在隱藏時添加一個類,就像我在jsfiddle中所做的那樣。這樣做的一個好處是,只要檢查它是否具有該類,就可以始終獲得菜單的狀態(隱藏或不隱藏)。

jsfiddle

$('.menu-toggle').click(function(){ 
     if ($('.menu').hasClass("hiddenRight")) { 
      alert('left 100%'); 
      $(this).text('keyboard_arrow_right'); 
      $('.menu').stop().animate({ 
       left: 0 
      }, 500); 
      $('.menu').removeClass("hiddenRight"); 
     } 
     else { 
      alert('left not 100%'); 
      $(this).text('menu'); 
      $('.menu').stop().animate({ 
       left: '100%' 
      }, 500); 
      $('.menu').addClass("hiddenRight"); 
     } 
    });