使用 jQuery 非常简单。这些是您应该采取的步骤。
- 使用固定定位将弹出窗口固定到屏幕的一侧
- 添加用户触发滑入/滑出效果的可点击区域
- 创建一个 jQuery 动画以通过负边距打开/关闭内容
- 在动画回调中更改触发器的显示方式(显示/隐藏)
重要 - toggle 事件在 jQuery 1.8 中已弃用并在 1.9 中删除。我原来的答案将不再有效。这个新版本适用于旧版本和新版本的 jQuery。此方法使用一个点击处理程序和一个名为hidden 的类来确定是否应在屏幕上/关闭弹出窗口进行动画处理。
http://jsfiddle.net/tzDjA/
jQuery
//when the trigger is clicked we check to see if the popout is currently hidden
//based on the hidden we choose the correct animation
$('#trigger').click( function() {
if ($('#popout').hasClass('hidden')) {
$('#popout').removeClass('hidden');
showPopout();
}
else {
$('#popout').addClass('hidden');
hidePopout();
}
});
function showPopout() {
$('#popout').animate({
left: 0
}, 'slow', function () {
$('#trigger span').html('Close'); //change the trigger text at end of animation
});
}
function hidePopout() {
$('#popout').animate({
left: -40
}, 'slow', function () {
$('#trigger span').html('Show'); //change the trigger text at end of animation
});
}
CSS
/* minimal CSS */
#popout {
position: fixed; /* fix the popout to the left side of the screen */
top: 50px;
left: -40px; /* use a negative margin to pull the icon area of the popout off the edge of the page */
width: 75px;
border: 1px dotted gray;
color: gray;
}
#trigger { /* create a clickable area that triggers the slide in/out effect */
position: absolute; /* position clickable area to consume entire right section of popout (add a border if you want to see for yourself) */
top: 0;
bottom: 0;
right: 0;
cursor: pointer;
}
原始答案(从 jQuery 1.9 起不起作用)
http://jsfiddle.net/WMGXr/1/
$('#toggle').toggle(
function() {
$('#popout').animate({ left: 0 }, 'slow', function() {
$('#toggle').html('Close');
});
},
function() {
$('#popout').animate({ left: -40 }, 'slow', function() {
$('#toggle').html('Show');
});
}
);
<div id="popout">
<div id="toggle">Show</div>
<br style="clear: both" />
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
</ul>
</div>
#popout { position: fixed; height: 100px; width: 75px; border: 1px dotted gray; background: darkblue; color: white; top:50px; left: -40px; }
#toggle { float: right; }