首页 > JS阻止默认冒泡无效

JS阻止默认冒泡无效

        // 点击屏幕收起发布框
        $(document).bind('click',function(event){
            event.stopPropagation();
            bottomNav.animate({bottom : -54 +'px'});

        });

        editIcon.bind('click',function(e){
            var bottomNavBottom = parseInt(bottomNav.css('bottom'));
            e.stopPropagation();

            // console.log(bottomNavBottom);
            if(bottomNavBottom == -54){
                bottomNav.animate({bottom : 0 });
                return;
            }
            
            bottomNav.animate({bottom : -54 +'px'});

            
        });

        // 改变文字颜色
        commentInput.bind('input',function(e){
            e.stopPropagation();

            var contentChange = $.trim(commentInput.val());
            // bottomNav.css({bottom : 0 });

            console.log(contentChange.length)
            if(contentChange.length > 0){
                commentSpan.css('color','#fff');
            }else{
                commentSpan.css('color','rgba(255,255,255,0.6)');

            }
            
        });

        commentSpan.bind('click', function(e) {
            e.stopPropagation();

            var content = $.trim(commentInput.val());
            var newContent = '';
            下面的代码省略...

我给document绑定了click事件,点击document的时候可以控制某个元素的bottom值。但是当我点击document的其他位置时确实可以实现,但是当我操作input的时候也会导致bottom的值和document一样。也就是我阻止冒泡失败了。请问是什么原因呢,求解。


我觉得应该是,对input额外绑定click事件,然后再阻止click事件冒泡。


你可能没有理解到事件冒泡的含义。

事件冒泡是子元素优先触发,父级元素后触发,最后冒泡到document元素。

如果你直接给document绑定事件,那肯定你点谁都会执行事件,你这里的阻止冒泡并没有什么意义。

假如你给input绑定了一个改变颜色的事件,给document绑定了一个改变bottom的事件。解释如下


$(document).bind('click', function() {
    // 改变元素bottom
    // 直接给document绑定了事件,这里的阻止冒泡并没有意义
})

commentInput.bind('click', function() {
    // 改变字体颜色
    // 如果不阻止冒泡,那么点击这个input,会先执行改变字体颜色,然后执行改变bottom的事件
    // 如果阻止了冒泡,就只会执行改变颜色的事件,而不会冒泡到document执行document上的事件
})

因此,如果你想要点击input不执行document的事件,只需要在input绑定事件的时候阻止冒泡就行了


<input id="J_ipt" type="text">
<button id="J_btn" type="button">button</button>
<script>
$(function(){
  $(document).on('click', function(){
    console.log('document.click');
  });
  $('#J_btn').on('click', function(e){
    e.stopPropagation();
    console.log('button.click');
  });
  $('#J_ipt').on('input', function(e){
    e.stopPropagation();
    console.log('input.input');
  }).on('click', function(e){
    e.stopPropagation();
    console.log('input.click');
  });
})
</script>

如果input要click的时候阻止冒泡,就要写代码组织冒泡,并没有看到你阻止input.click的代码。

input是输入字的时候触发的事件,不是click事件

【热门文章】
【热门文章】