我发现解决此问题的最佳方法是将元素放置在相同大小的不可见包装中。包装器应该有overflow: hidden
并且元素应该被推到包装器的边缘之外,而不是在<body>
.
这个解决方案的诀窍是实际上没有任何东西离开屏幕,因此浏览器不会尝试增加视口大小来补偿。相反,包装器位于屏幕边缘,侧边栏位于其中。将包装器视为不透明贴图。
包装器还必须调整为 0,这样它就不会在文档顶部不可见,并且可能会抓取不适合它的点击。
这是实践中解决方案的示例。我使用 jQuery 来操作 CSS,但任何 JavaScript 库(或没有)都可以解决问题。请注意,除非侧边栏包装器按比例缩小,否则“点击器”div 将不可点击。
$('.sidebar-inner').on('click', function() {
$(this).css('right', -250);
$(this).closest('.sidebar-outer').css('width', 0);
});
$('.clicker').on('click', function() {
alert('CLICKED!');
});
body
{
background-color: red;
font: 12pt sans-serif;
}
.sidebar-outer
{
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
width: 250px;
-webkit-transition: width 0.2s ease-out;
-moz-transition: width 0.2s ease-out;
transition: width 0.2s ease-out;
overflow: hidden;
z-index: 999;
}
.sidebar-inner
{
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
width: 250px;
padding: 10px;
box-sizing: border-box;
-webkit-transition: right 0.2s ease-out;
-moz-transition: right 0.2s ease-out;
transition: right 0.2s ease-out;
background-color: cornflowerblue;
cursor: pointer;
}
.clicker
{
position: absolute;
width: 50px;
height: 50px;
top: 10px;
right: 10px;
padding: 10px;
background-color: green;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="sidebar-outer">
<div class="sidebar-inner">
Click to hide
</div>
</div>
<div class="clicker">Click me!!</div>