我有一个样式化的按钮。
这个按钮有一个父元素,会触发一个可折叠的事件。我不知道如何防止这个按钮触发它父元素的可折叠事件。这是由于按钮样式的 pointer-events: none 导致的。
谢谢。
pointer-events: none;
这个按钮有一个父元素,会触发一个可折叠的事件。我不知道如何防止这个按钮触发它父元素的可折叠事件。这是由于按钮样式的 pointer-events: none 导致的。
谢谢。
pointer-events: none;
假设以下是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();
});
pointer-events:none
属性的元素不会触发事件处理程序。 - Oriolpointer-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
),但现在您可以区分用户是单击了您的元素还是其子元素。
问题:旧版IE无法使用捕获阶段。
优点:由于它不适用于旧版IE,因此您不必担心诸如
e = e || window.event
e.target || e.srcElement
if (e.stopPropagation) { e.stopPropagation(); } else { e.calcelBubble=true; }
e.target === this
检查,或者停止传播,但我不确定对于没有指针事件的元素是否起作用,当单击此类元素时,你实际上是直接穿过它点击父元素,因此,在某种程度上,至少如果该元素在没有指针事件的元素“后面”,就像这个整体的意义一样。 - adeneo