jquery 点击元素实现背景色改变,点击元素以外任意地方还原该元素背景色

jquery 点击元素实现背景色改变,点击元素以外任意地方还原该元素背景色

html代码如下:

<!doctype html>
<html>
<head>
	<title>ssssds</title>
	<script src="jquery-3.1.1.min.js"></script>
	<script type="text/javascript" src="s.js"></script>
	<style type="text/css">
		div{
			width: 300px;
			height: 300px;
			border:3px red solid;
		}
	</style>
</head>
<body>
	<div></div>
</body>
</html>



jquery代码如下:


$(function(){
	$("div").click(function(){
		$(this).css("background-color","red");
		console.log("3");
	});

	$(document).click(function(){
		console.log("1");
		$("div").css("background-color","white");
	});

	$("div").click(function(event){
		console.log("2");
    	event.stopPropagation();
	});
});

首先,定义点击div改变背景色事件;

   

$("div").click(function(){
		$(this).css("background-color","red");
		console.log("3");
	});

其次,定义点击整个文档事件,也就是点击除了div元素外的内容,还原div的背景色。

   

	$(document).click(function(){
		console.log("1");
		$("div").css("background-color","white");
	});
但是这种写法,点击div也会触发还原背景色的事件,所以要阻止冒泡事件,添加如下代码:
        
$("div").click(function(event){
	console.log("2");
    	event.stopPropagation();
});




  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值