2016-03-07 136 views
0

我出現時,這個功能它叫如何在外部點擊時關閉邊欄?

var toggleSidebar = function() { 
    $('#sidebar .arrow-box').click(function() { 
     if (s === 0) { 
      s = 1; 
      $('#sidebar').css('left', '0'); 
      $('#sidebar .arrow').removeClass('dir-two'); 
      $('#sidebar .arrow').addClass('dir-one'); 
      $('#content').css('padding-left', '0'); 
     } else { 
      s = 0; 
      $('#sidebar').css('left', '-300px'); 
      $('#sidebar .arrow').addClass('dir-two'); 
      $('#sidebar .arrow').removeClass('dir-one'); 
      $('#content').css('padding-left', '300px'); 
     } 
    }); 
}; 

但正如你看到的,我可以打開並且只有特定的元素,當點擊關閉側邊欄右側欄,我應該怎樣才能做到,當我將其關閉點擊外面?

以防萬一:根據UX我無法在側欄出現時在整個視圖中使用深色背景。

+0

你能結合'的(「模糊」 ...)'邊欄元素本身上做隱藏? – ochi

回答

0

看看這個: How do I detect a click outside an element?

$('html').click(function() { 
    // Hide the sidebar 
}); 

$('#sidebar').click(function(event){ 
    event.stopPropagation(); // prevents executing the above event 
}); 
+0

我相信event.stopPropagation();會阻止他的點擊處理程序按照您寫入的方式在該側面板中的任何鏈接上工作,而不僅僅是單擊時阻止其關閉。 – Korgrue

+0

這些鏈接會很好,因爲它們位於#sidebar的「上方」,所以它們在傳播樹中較早處理。 – jdabrowski

0

只是檢測包括頁面中的元素的點擊。並防止側邊欄上的點擊冒泡到該元素。

$("body").click(function() { 
    toggleSidebar(); 
}); 

$("#sidebar").click(function (e) { 
    e.stopPropagation(); 
}); 
+3

當用戶點擊頁面上的任何位置時,這也會將其切換爲打開狀態。他們很可能不想要那樣 – KyleK

0

測試點擊的目標。如果它與要關閉的目標不匹配,請關閉它。所有其他元素都是身體的孩子 - 所以點擊面板外的任何地方都會獲取點擊目標。

$sidebar = $('#sidebar'); 
$("body").click(function(event) { 
    var a = event.target; 
    if(a === $sidebar){ 
//close the sidebar 
//you may also want to test if it is actually open before calling the close function. 
} 
}); 
0

我會做這樣的... (DEMO HERE)

sideBarOpen=false;  

function openSidebar(){ 
    sideBarOpen = true; 
    $('#sidebar').css('margin-left', '0'); 
    $('#sidebar .arrow').removeClass('dir-two'); 
    $('#sidebar .arrow').addClass('dir-one'); 
    $('#content').css('padding-left', '0'); 
} 

function closeSidebar(){ 
    sideBarOpen=false; 
    $('#sidebar').css('margin-left', '-300px'); 
    $('#sidebar .arrow').addClass('dir-two'); 
    $('#sidebar .arrow').removeClass('dir-one'); 
    $('#content').css('padding-left', '300px'); 
} 

$(document).click(function(event) { 
    var target = $(event.target); 
    if(sideBarOpen){ 
     closeSideBar(); 
    } else { 
    if(target.is('#sidebar')){ 
     openSideBar(); 
    } 
    } 
}); 

如果用戶點擊任何地方,將會關閉,但打開它,如果用戶點擊側邊欄

UPDATE

如果你還想要點擊側欄內的東西 只需給他們一個班級,並添加到target.is檢查。

舉例酒吧裏面的鏈接

 <a href='#' class='menuLinks'>Test Link</a> 

然後您單擊處理

if(target.is('#sidebar') || target.is('.menuLinks')){ 
     openSideBar(); 
    } else { 
     if(sideBarOpen){ 
     closeSideBar(); 
    }