bind、click、mouseover、mouseout及简写实现显示与隐藏效果

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LzzMandy/article/details/82589014

1、$().bind("click", function() {...........});也可以写成  $().click(function() {..........});

2、$().bind("mouseover", function() {...........})

          .bind("mouseout", function() {...........});

也可以写成
$().mouseover(function() {...........})

          .mouseout( function() {...........});

写成第二种方式更简单,

3、样例:实现点击“标题”,显示或隐藏内容;或者鼠标滑过显示或隐藏内容

4、源码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>绑定事件练习</title>
<script src="scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
	// 带有bind的写法
	$("#outSet h5.head").bind("click", function() {
		// 获取要显示与隐藏的内容
		var $showOrHideContent = $(this).next();
		// 判断需要显示与隐藏的内容是否存在
		if ($showOrHideContent.is(":visible")) {
			$showOrHideContent.hide();
		} else {
			$showOrHideContent.show();
		}
	});
	// 另一种简写方式
	$("#outSet h5.head").click(function() {
		// 获取要显示与隐藏的内容
		var $showOrHideContent = $(this).next();
		if ($showOrHideContent.is(":visible")) {
			$showOrHideContent.hide();
		} else {
			$showOrHideContent.show();
		}
	});

	// 带有bind的写法
	$("#outSet h5.head").bind("mouseover", function() {
		$(this).next().show();
	}).bind("mouseout", function() {
		$(this).next().hide();
	});
	// 另一种简写方式
	$("#outSet h5.head").mouseover(function() {
		$(this).next().show();
	}).mouseout(function() {
		$(this).next().hide();
	});
})
</script>
<style type="text/css">
*{margin:0;padding:0;}	
#outSet { width: 300px; border: 1px solid #0050D0;margin:50px auto; }
.head { height:24px;line-height:24px;text-indent:10px;background: #96E555; cursor: pointer;width:100%; }
.content { padding: 10px; text-indent:24px; border-top: 1px solid #0050D0;display:block;display:none; }
</style>
</head>
<body>
<div id="outSet">
	<h5 class="head">绑定事件,显示与隐藏的写法</h5>
	<div class="content">
		君不见黄河之水天上来,奔流到海不复回。
君不见高堂明镜悲白发,朝如青丝暮成雪。
人生得意须尽欢,莫使金樽空对月。
天生我材必有用,千金散尽还复来。
烹羊宰牛且为乐,会须一饮三百杯。
岑夫子,丹丘生,将进酒,杯莫停。
与君歌一曲,请君为我侧耳听。
钟鼓馔玉不足贵,但愿长醉不复醒。
古来圣贤皆寂寞,惟有饮者留其名。
陈王昔时宴平乐,斗酒十千恣欢谑。
主人何为言少钱,径须沽取对君酌。
五花马,千金裘,
呼儿将出换美酒,与尔同销万古愁。
	</div>
</div>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/LzzMandy/article/details/82589014