2017-06-15 59 views
0

我有一個側邊欄可以轉換爲較小屏幕尺寸的選項卡。這主要是用css完成的,使用JavaScript打開和關閉選項卡。當標籤打開時,我已經做好了讓用戶可以點擊屏幕上的任何地方來關閉它。響應式邊欄選項卡和點擊事件切換

我的resize()函數會將標籤轉換回側邊欄,但是,如果用戶在較小尺寸的標籤上單擊,然後放大其瀏覽器,單擊屏幕上的任意位置將使側邊欄消失。

基本上,我需要能夠做的是去除的onclick我已經在這裏設置,像

if($(window).width() > 751 
{ 
    {remove the event set up in $(document).click(function(e)} 
} 

我使用jQuery「.off」功能嘗試;停止傳播 - 似乎沒有任何工作。即使使用正確的語法,我也不確定.off會做到這一點。我想,可能會關閉任何事件點擊,當然,我不想這樣做。事情就需要在屏幕尺寸調整爲大於751

<script type="text/javascript"> 
    $(document).ready(function() 
    { 
     $('#SideTab').click(function() 
     { 
      // Actual width is 340, allowing for tab (#SideTab) to show 
      // Toggle Sidebar open or closed 
      if($('#Sidebar1').css('margin-left') != '-300px') 
      { 
       $('#Sidebar1').css('margin-left', '-300px'); 
      } 
      else 
      { 
       // At 0px, Sidebar is showing 
       // Event handler allows for Sidebar to close when item on 
       // Sidebar is clicked, as well as anywhere outside of 
       // Sidebar. 
       $('#Sidebar1').css('margin-left', '0px'); 
       $(document).click(function(e) 
       { 
        if(!($(e.target).is("#Sidebar1") || $(e.target).closest("#Sidebar1").length) || $(e.target).is(".cbp-filter-item")) 
        { 
         // Hide Sidebar 
         $('#Sidebar1').css('margin-left', '-300px'); 
        } 
       }); 
      } 
     }); 
     $(window).resize(function() 
     { 
      if($(window).width() > 751) 
      { 
       $('#Sidebar1').css('margin-left', '0px'); // Show Sidebar 
      } 
      else 
      { 
       $('#Sidebar1').css('margin-left', '-300px'); // Hide Sidebar 
      } 
     }).resize(); 
    }); 
</script> 

只是重申恢復正常,此代碼工作正常,在任何屏幕尺寸。當用戶以較小的屏幕尺寸單擊選項卡時,會出現問題,然後將屏幕調整到側邊欄處於活動狀態的位置(頁邊空白:0)。在這些情況下,點擊屏幕上的任何位置都會使邊欄消失。當屏幕尺寸大於751時,邊欄應始終顯示。

回答

0

這非常簡單。不知道爲什麼這裏坐在這裏沒有迴應。 (雖然現在看來,答案是很明顯的。) 簡單地改了行

if(!($(e.target).is("#Sidebar1") || $(e.target).closest("#Sidebar1").length) || $(e.target).is(".cbp-filter-item")) 

if(($(window).width() < 752) && (!($(e.target).is("#Sidebar1") || $(e.target).closest("#Sidebar1").length) || $(e.target).is(".cbp-filter-item"))) 
+0

認爲你需要使用stopPropagation?這裏有一篇很棒的文章:https://css-tricks.com/dangers-stopping-event-propagation/ – RationalRabbit

相關問題