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(); });