一种方法是将您的按钮放在滑动父级中
jsFiddle
<div id="popout">
<div id="toggle">Toggle</div>
Now the button animates with me! yey
</div>
CSS:
#popout {
position: fixed;
width: 250px;
background-color: #EBEBEB;
color: black;
top: 0px;
right: -250px;
transition: 500ms transform ease-in-out;
height: 100px;
}
#toggle {
position: absolute;
right: 250px; /* same as parent width */
width: 40px;
height: 40px;
}
还请注意,您使用 .toggle(cb1, cb2) 的方式已从 jQuery 1.8 中弃用并从 jQuery 1.9 中删除,因此如果有一天您希望将 jQuery 更新到当前版本,则必须切换一种不同的方式,例如:
$('#toggle').click(function(){
var io = this.io ^= 1; // Toggles 1,0,1,0,1....
$('#popout').animate({ right: io ? 0 : -250 }, 'slow');
});
demo using jQuery 2.1.3
或者没有 1/0 切换,您可以检索元素的当前正确位置:
var $popout = $('#popout')
$('#toggle').click(function(){
var isRight = parseInt($popout.css("right"), 10) < 0;
$('#popout').animate({ right: isRight ? 0 : -250 }, 'slow');
});
demo using the current right position
CSS3 转换和 jQuery 切换状态
始终保持滑动父级内的按钮,您可以使用 CSS3 执行动画,并使用 jQuery 在单击时切换类,例如:
jQuery(function( $ ) {
$('#toggle').click(function(){
$("#popout").toggleClass("opened");
});
});
#toggle {
position: absolute;
right: 290px; /* push it right */
width: 40px;
height: 40px;
}
#popout {
position: fixed;
width: 250px;
height: 100px;
background-color: #EBEBEB;
top: 0px;
right: -250px;
/*overflow:auto; REMOVE SO WE CAN SEE THE INNER BUTTON */
/* SET OVERFLOW TO AN INNER CONTENT DIV IF NEEDED */
transition: 0.5s;
}
#popout.opened{ /* opened class is toggled by jQ */
right: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="popout">
<div id="toggle">Toggle</div>
content
</div>