.animate只工作一种方式



我正在使用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时,您需要使用事件委派:

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

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


另一种方法是在一个函数中使用condition:
$("#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);
        }
    });
});

最新更新