.animate 仅以一种方式工作

.animate only working 1 way

我正在使用 jquery 动画来打开和关闭边栏,打开边栏时效果很好,但关闭时不起作用

代码如下:

$(function() {
 $("#sidebar_open").bind("click", function(){
     var $inner = $("#sidebar");
     $inner.stop().animate({width:'200px'},{queue:false, duration:600, easing: 'swing'});
  $(".nav-btn").html('<center><img id="sidebar_close" src="images/arrow_left.png" width="30" style="cursor:pointer; margin:0;"></center>');
 });
 $("#sidebar_close").bind("click", function(){
     var $inner = $("#sidebar");
     $inner.stop().animate({width:'62px'},{queue:false, duration:600, easing: 'swing'});
  $(".nav-btn").html('<center><img id="sidebar_open" src="images/arrow_right.png" width="30" style="cursor:pointer; margin:0;"></center>');
 });
});
div#sidebar {
 width:62px;
 position:fixed;
 height:87%;
 left:0;
 background:#42515f; 
 top:96px;
 padding-top:3%;
 overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sidebar">
 <a href="#"><img src="images/dashboard_icon.png" width="18"> Dashboard</a>
    <div class="nav-btn" style="width:100%; float:left; margin-top:50px;"><center><img id="sidebar_open" src="images/arrow_right.png" width="30" style="cursor:pointer; margin:0;"></center></div>
</div>

如有帮助将不胜感激

当您动态替换 img 时,您需要使用 event-delegation:

$("#sidebar").on("click", '#sidebar_open',function () {

$("#sidebar").on("click", '#sidebar_close',function () {

Demo


另一种方法是在一个函数中使用条件:

$("#sidebar").on("click", '#sidebar_img', function () {

    var $inner = $("#sidebar");
    var sidebarWidth;
    var src;
    if ($inner.hasClass('sidebar_closed')) {
        sidebarWidth = '200px';
        src = 'images/arrow_left.png';
    } else {
        sidebarWidth = '62px';
        src = 'images/arrow_right.png';
    }
    $inner.stop().animate({
        width: sidebarWidth
    }, {
        queue: false,
        duration: 600,
        easing: 'swing',
        complete: function () {
            $inner.toggleClass('sidebar_open sidebar_closed');
            $('#sidebar_img').attr('src', src);
        }
    });

});

Demo