调用此函数时,会出现一个右侧边栏
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');
}
});
};
但是正如您所看到的,只有在单击该特定元素时我才能打开和关闭该侧边栏,当我单击外部时我应该做什么才能关闭它?
以防万一:根据用户体验,当侧边栏出现时,我无法在整个 View 中使用深色背景。
最佳答案
测试点击的目标。如果它与您要关闭的目标不匹配,则将其关闭。所有其他元素都是正文的子元素 - 因此单击面板之外的任何位置都将检索单击目标。
$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.
}
});
关于javascript - 点击外部时如何关闭侧边栏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35852911/