<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> $(document).bind('click', function(e) { var e = e || window.event; //浏览器兼容性 var elem = e.target || e.srcElement; while (elem) { //循环判断至跟节点,防止点击的是div子元素 if (elem.id && (elem.id == 'test' || elem.id == 'test2')) { return; } elem = elem.parentNode; } $('#a').css('display', 'none'); //点击的不是div或其子元素 }); </script> </head> <body> <div id="a"> <div id="test" style=" 300px; height: 300px; background-color: palegreen;">
测试测试测试测试
</div> <div id="test2" style="100px;height:100px;background:gold;">测试测试测试测试</div> </div> </body> </html>