|
工作中遇到点击body上的任意位置需要将另一个元素进行隐藏。html代码如下:
<div class="anniu">按钮</div> <div class="contain"></div>配上一个很简陋的css样式: body { width: 100%; height: 600px; } .show { display: block !important; } .anniu { width: 50px; height: 50px; background: tan; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; } .contain { width: 300px; height: 300px; background: red; } 然后就开始了踩坑之旅,js代码开始了: $('.anniu').click(function() { if ($('.contain').hasClass('show')) { $('.contain').hide().removeClass('show'); } else { $('.contain').addClass('show'); } }) $('body').bind('click', function() { if ($('.contain').hasClass('show')) { $('.contain').hide().removeClass('show'); } }); 然后以为就完成了,到页面上一点,发现好像并不能生效,咋回事呢? 再仔细一想,我点了按钮,会不会是事件冒泡到了body了呢? 于是,我又添上了阻止事件冒泡的代码: function stopPropagation(e) { if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true; } $('.anniu').bind('click', function(e) { stopPropagation(e); }); 测试,成了........ |
|
最新喜欢: |
|
沙发#
发布于:2020-01-06 17:03
试试这个方法,没用到show类名;
$('.anniu').click(function(e){ e.stopPropagation(); $('.contain').fadeToggle(); }) $('body').click(function(){ $('.contain').fadeToggle(); }) |
|
|
板凳#
发布于:2018-10-23 10:12
楼主的解决思路,相当6
|
|
|