【发布时间】:2017-06-15 23:46:14
【问题描述】:
我有一个侧边栏,可以转换为用于较小屏幕尺寸的选项卡。这主要是通过 css 完成的,使用 JavaScript 打开和关闭选项卡。 When the tab is open, I've made it so that the user can click anywhere on the screen to close it.
我的 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 时,侧边栏应始终显示。
【问题讨论】:
标签: javascript jquery css responsive-design tabs