在'div'上禁用鼠标事件

Ret*_*hna 3 html javascript css events

我在使用'pointer-events'css样式禁用鼠标事件时遇到了一个有趣的问题.

请参考小提琴.它有一个父项和两个子div,我将'pointer-events'作为'none'给其中一个孩子.如果我单击该div,则不会触发其鼠标侦听器(这是预期的),但会触发其父div的鼠标事件.

$('#parent').click(function(){
   console.log("Parent clicked"); 
});
Run Code Online (Sandbox Code Playgroud)

如果我点击了为鼠标事件禁用的子节点,如何在父div上禁用鼠标事件?

一种选择是在父点击上使用"if"条件进行过滤.但我不需要它,因为我想在父母后面的'divs'上听老鼠事件.

请提供一些帮助:)

谢谢,雷斯纳

Mat*_*eus 8

我无法使指针事件像我预期的那样工作,所以我改变了javascript以实现你想要的.我所做的是对child2的event.stopPropagation,所以你可以点击他,只触发他的点击事件,而不是他父母的点击事件.顺便说一句,我对jquery知之甚少,所以我写了一个混合beetwen纯javascript和jquery,希望有人可以帮我翻译.

这是小提琴

CSS:

child1 {

background-color:#ff0000;
width:100px;
height:100px;
pointer-events: all;
Run Code Online (Sandbox Code Playgroud)

}

{的child2

background-color:#00ff00;
width:100px;
height:100px;
pointer-events: all;
Run Code Online (Sandbox Code Playgroud)

}

父{

 pointer-events: none;
Run Code Online (Sandbox Code Playgroud)

}

使用Javascript:

$(document).ready(function(){
    document.getElementById('child1').addEventListener('click', function(){
        console.log("child1 clicked");
    }, false);

    document.getElementById('child2').addEventListener('click', function(e){
        e.stopImmediatePropagation();
        console.log("child2 clicked");
    }, false);

    document.getElementById('parent').addEventListener('click', function(){
        console.log("Parent clicked");
    }, false);
});
Run Code Online (Sandbox Code Playgroud)