我正在使用jquery animate打开&关闭侧边栏,打开侧边栏时工作正常,但关闭时不起作用
以下是代码:
$(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>
任何帮助都会很棒
答案 0 :(得分:0)
当您动态替换img
时,您需要使用event-delegation:
$("#sidebar").on("click", '#sidebar_open',function () {
和
$("#sidebar").on("click", '#sidebar_close',function () {
<强> Demo 强>
另一种方法是在一个函数中使用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);
}
});
});
<强> Demo 强>