如果元素被 css 隐藏,则 MouseEvent 被吞下

MouseEvent swallowed if element hidden by css

我有一个带有 onClick 事件的元素(它是一个图标)。我只想在满足某些条件时显示该元素,并且我能够读取该条件并完全从 CSS 处理 show/hide。

如果元素可见并且我点击它,我希望它执行两个操作:

  1. 触发JS事件,
  2. 隐藏元素。

但是 CSS 以某种方式隐藏元素的速度比 JS 响应的速度快,并且根本不会触发事件。

我没有研究过JS中的事件系统是如何工作的,但在我看来,首先CSS被解析,然后JS事件系统接收有关某些[=13上的点击事件的信息=]位置,元素已经没有了,所以不会触发事件。

我尝试了几个 CSS 选项来隐藏包含此 CSS 属性的元素:

display: block / none;
visibility: visible / hidden;
z-index: 1 / -1;
width|height: auto / 0;
top|left|right|bottom: 0 / -9999px;

如果我用 opacity: 1 / 0 隐藏元素,事件 触发的,因为元素在它所在的位置保持可点击,但这也是问题,因为我不希望该元素在不可见时可点击。

有什么技巧吗,如何通过纯 CSS 隐藏元素,同时在其上触发事件?

我尝试用 transition: all 160ms; 延迟 CSS,但是隐藏元素的 CSS 规则是即时的(您不能转换 displayvisibilityz-index) 所以这没有用。

我在GoogleChrome53.0.2785.116平台Win10 x64

挑战这个问题

编辑:JSBin

点击问题是当项目被隐藏时,点击动作无法完成。所以你可以切换到 mousedown 而不是 click

document.getElementById("test_click").addEventListener("mousedown", function(){
    console.log("Clicked");
});
#test_container {
      position: relative; 
      display: inline-block;
    }
    
    #test_click {
      position: absolute;
      display: none;
      left: 100%;
      top: 50%;
    }
    
    #test_input:focus + #test_click {
      display: inline;
    }
    
    #test_input:focus + #test_click:hover {
      color: dodgerblue;
      cursor: pointer;
    }
<div id="test_container">
    <input type="text" id="test_input" placeholder="focus me...">
    <span id="test_click">CLICK</span>
  </div>
  
  <h3>Click on the input and "CLICK" appears, click on "CLICK" and "CLICK" hides and no JS event is triggered although it is attached. Then, remove "display: none;" from CSS and try click again, the JS event is triggered.</h3>

或添加 css 以在悬停时保持元素可见

document.getElementById("test_click").addEventListener("click", function(){
    console.log("Clicked");
});
#test_container {
      position: relative; 
      display: inline-block;
    }
    
    #test_click {
      position: absolute;
      display: none;
      left: 100%;
      top: 50%;
    }
    

    #test_click:hover,
    #test_input:focus + #test_click {
      display: inline;
    }
    
    #test_input:focus + #test_click:hover {
      color: dodgerblue;
      cursor: pointer;
    }
<div id="test_container">
    <input type="text" id="test_input" placeholder="focus me...">
    <span id="test_click">CLICK</span>
  </div>
  
  <h3>Click on the input and "CLICK" appears, click on "CLICK" and "CLICK" hides and no JS event is triggered although it is attached. Then, remove "display: none;" from CSS and try click again, the JS event is triggered.</h3>