2013-09-24 107 views
5

我有了一个风格停止事件冒泡的残疾人元素

pointer-events: none; 

一个按钮,此按钮执行一个可折叠的事件父元素。我不知道如何防止这个按钮触发其父元素可折叠事件。没有

感谢

+0

如果您向我们展示html,然后我们可以帮助:) – Archer

+0

指针事件不是禁用元素的方式,它只是取消ls所有指针事件,并且对于你正在做的事情需要基础元素上的指针事件很有帮助。 – adeneo

+1

您需要e.stopPagagation() – Krishna

回答

3

假设下面的html:

<div class="collapsible"> 
    <button>Hi</button> 
</div> 

你可以做这样的事情:

$('.collapsible').click(function(e) { 
    if ($(this).children('button').css('pointer-events') == 'none') return; 

    //do collapse 
}); 

这是由于按钮样式是指针的事件引起的或者可能是这样的:

$('.collapsible').click(function(e) {   
    //do collapse 
}); 

$('.collapsible button').click(function(e) { 
    if ($(this).css('pointer-events') == 'none') 
     e.stopPropagation(); 
}); 
+1

带有'pointer-events:none'的元素不会触发事件处理程序 – Oriol

1

正如@adeneo所说,如果你在孩子上使用pointer-events: none,那么父母的事件监听器就无法知道目标是自己还是孩子。 这就像当您单击段落中的某些文本时,事件侦听器无法知道您是否单击了文本或段落的填充。

然后,您可以使用

document.getElementById('outer').onclick = function(e) { 
    /* your code */ 
}; 
document.getElementById('outer').addEventListener('click', function(e) { 
    if(e.target !== this) { 
     e.stopPropagation(); 
    } 
}, true); 

pointer-events: none

这样,你使用捕获阶段,所以你可以阻止儿童的事件处理程序的执行(如pointer-events: none),但现在你可以区分用户是否点击你的元素或其子。

Demo jsFiddle

问题:你不能老版本的IE中使用捕捉阶段。

优势:因为它不旧IE浏览器,你不必担心像

  • e = e || window.event
  • e.target || e.srcElement
  • if (e.stopPropagation) { e.stopPropagation(); } else { e.calcelBubble=true; }