学习 jQuery:淡出菜单 - 替换内容

Avatar of Chris Coyier
Chris Coyier

DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 $200 免费信用额度!

2013 年 1 月更新: 此类最佳实践 此处详细介绍
2010 年 5 月更新: 我认为这篇文章已 **弃用**。我有一篇 更新的文章,其中涵盖了与本文相同类型的材料,但包含更多功能、更新的技术和更佳实践。

fadingmenu.png

我对 jQuery 了解得越多,它就越自然。这可能是因为它与 CSS 密切相关。从设计的角度来看,jQuery 的语法是

“当我 **这样做** 时,让 **CSS 这样做**。”

更常见的口号是

找到某物,做某事。

…这也非常棒。

因此,现在您不必将 CSS 视为页面布局和页面加载时的样式方式,而是可以将其用于动画,并在页面发生事件时动态更改它以做出反应。例如,菜单。您可以使用点击菜单时发生的 “click” 事件来执行大量操作。

此示例页面包含三个菜单项和三个内容区域:首页、关于和联系。默认情况下,首页按钮处于选中状态,这意味着它的菜单图形处于完全不透明状态,并且显示了它的内容区域

#home {
	display: block;
	padding: 30px;
}
#home-button {
	opacity: 1.0;
	border-bottom: 1px solid black;
}

默认情况下,其他菜单项已淡出,并且其内容区域隐藏,如下所示

#about {
	display: none;
	padding: 30px;
}
#about-button {
	opacity: 0.5;
	border-bottom: 1px solid black;
}

使用 jQuery,我们可以监听该 click 事件,然后做出相应的操作。这是我们希望发生的事情

  • 淡入被点击的菜单项。
  • 淡出所有其他菜单项。
  • 显示相应的内容区域。
  • 隐藏所有其他内容区域。

由于首页按钮默认处于活动状态,因此让我们看一下 **关于按钮** 的 jQuery javascript

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
	$(document).ready(function(){
		$("#about-button").click(function(){ 
			$(this).animate({ 
				opacity: 1.0,
				borderWidth: 5
			}, 600 );
			$("#home")
				.css({
					display: "none"
				});
			$("#about")
				.css({
					display: "block"
				});
			$("#contact")
				.css({
					display: "none"
				});
			$("#home-button").animate({ 
				opacity: 0.5,
				borderWidth: 1
			}, 600 );
			$("#contact-button").animate({ 
				opacity: 0.5,
				borderWidth: 1
			}, 600 );
		});
	});
</script>

您的完整 javascript 代码将包含所有三个按钮的类似代码段。正如我之前提到的,我仍在学习,因此可能存在更智能的编写方式,但这只是基本知识,而且它们有效。

更新:这更智能。

$("#page-wrap div.button").click(function(){
	
	$clicked = $(this);
	
	// if the button is not already "transformed" AND is not animated
	if ($clicked.css("opacity") != "1" && $clicked.is(":not(animated)")) {
		
		$clicked.animate({
			opacity: 1,
			borderWidth: 5
		}, 600 );
		
		// each button div MUST have a "xx-button" and the target div must have an id "xx" 
		var idToLoad = $clicked.attr("id").split('-');
		
		//we search trough the content for the visible div and we fade it out
		$("#content").find("div:visible").fadeOut("fast", function(){
			//once the fade out is completed, we start to fade in the right div
			$(this).parent().find("#"+idToLoad[0]).fadeIn();
		})
	}
	
	//we reset the other buttons to default style
	$clicked.siblings(".button").animate({
		opacity: 0.5,
		borderWidth: 1
	}, 600 );
	
});