点击空白处让弹窗隐藏

来源:互联网 发布:哭 知乎 编辑:程序博客网 时间:2024/06/04 18:31

比如,登录框等,点击弹窗外的其它地方让弹窗消失。

很简单,但要注意两个问题:

1.firefox对event的兼容性

2.冒泡事件


上代码:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>hide</title><script src="jquery.min.js"></script><style>.box{margin: 100px auto;width: 200px;height: 200px;background-color: #E6BBFC;display: none;}</style></head><body><button class="btn">点我出现弹窗</button><div class="box"></div><script>$(function(){$('.btn').click(function(ev){var event = ev || event;  // firefox的兼容性event.stopPropagation();  // 阻止冒泡事件$('.box').show();});// 点击弹窗时,阻止冒泡事件$('.box').click(function(ev){var event = ev || event;event.stopPropagation();});$(document).click(function(){$('.box').hide();});})</script></body></html>