之前文章《”关闭/显示侧边栏”最简代码版》,先来看看其中的jQuery代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 
$('#close-sidebar a').toggle(function(){
 
	$(this).text("显示侧边栏");
 
	$('#sidebar').hide();
 
	$('#content').animate({width: "960px"}, 1000);
 
	},function(){
 
	$(this).text("关闭侧边栏");
 
	$('#sidebar').show();
 
	$('#content').animate({width: "705px"}, 800);
 
});

这段代码有个小小不完美的地方的,其实也有多个留心的童鞋发现并向我反馈过:

当点击“显示侧边栏”时,浏览器右侧的滚动条“急剧变化”,若侧边栏比较长更是明显……

其实当点击“显示”,侧边栏立即就显示出来了,只是主体的宽度还未缩回,它就被压在主体下面,页面的高度也随之增加,0.8s后才得以跳上来。

这与我们之前写代码的期望有点出入:点击“关闭”,侧边栏消失,主体宽度伸长;点击“显示”,主体宽度缩回,侧边栏显现。

处理这个小问题,首先想到的是用jQuery的fadeIn/fadeOut,轻松解决,可杯具的是经过这个淡入淡出后的字体,在IE下会变得惨不忍睹,尤其是雅黑。怎么办呢?

再次看《jQuery1.4中文文档》,发现新增了一个函数,可将队列中的函数延时执行:

.delay()

用这个函数也轻松解决,调整后的jQuery代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 
$('#close-sidebar a').toggle(function(){
 
	$(this).text("显示侧边栏");
 
	$('#sidebar').hide();
 
	$('#content').animate({width: "960px"}, 1000);
 
	},function(){
 
	$(this).text("关闭侧边栏");
 
	$('#sidebar').delay(800).show(0);
 
	$('#content').animate({width: "705px"}, 800);
 
});

可,用最新版1.4的童鞋并不多,还是通过网络搜索学习,原来早有另外一种书写格式可实现这个函数的功能,经过尝试,当当当当,完美版出现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
$('#close-sidebar a').toggle(function(){
 
	$(this).text("显示侧边栏");
 
	$('#sidebar').hide();
 
	$('#content').animate({width: "960px"}, 1000);
 
	},function(){
 
	$(this).text("关闭侧边栏");
 
	$('#content').animate({width: "705px"}, 800, function(){$('#sidebar').show();});
 
});

把原7、8两行代码合并,即实现了主体宽度缩回后,侧边栏再显示!

OK,到此本文的任务已经完成,下面分享我使用“关闭/显示侧边栏”的jQuery代码:

 
$('#close-sidebar a').toggle(function(){
 
	$(this).text("显示侧边栏")
 
	$('#sidebar').hide().prev().animate({width: "960px"}, 1000);
 
	},function(){
 
	$(this).text("关闭侧边栏")
 
	$('#sidebar').delay(800).show(0).prev().animate({width: "705px"}, 800);
 
});

如果你的主题侧边栏和主体的HTML结构是同级的,并且调用的是jQuery1.4版,就可以使用上述代码啦~