首页 > 解决方案 > 如何将事件监听器绑定到特定的 div 元素?

问题描述

我正在编写一个脚本,该脚本基于绑定到document(目前)的事件(keydown/up)执行一些操作。

当某个键与 一起按下时shift-key(e.g shift + a),会触发一些动作。

它正在工作,只是我想将事件侦听器绑定到特定div元素。

如果我有以下HTML内容,为什么无法将事件侦听器绑定到div具有 id 属性的最外层元素?

<div id="some-id" style="position: absolute; left: 0px; top: 0px;">
  :
  <div style="width: 100%; height: 100%; position: relative; left: 0px; top: 0px; padding: 0px; margin: 0px;">
    :
    <div style="width: 100%; height: 100%; position: absolute; left: 0px; top: 0px; padding: 0px; margin: 0px;">
      :
    </div>
  </div>
</div>

标签: javascriptjquery

解决方案


这是因为您的 div 是空的,因此它不占用任何宽度或高度,因此在任何 div 上都不会触发任何事件。尝试向 div 添加一些内容。或者尝试设置任何最里面的 div 的min-heightmin-width属性。

document.getElementById('some-id').addEventListener('click', () => {
  console.log('The click is working')
})
<div id="some-id" style="position: absolute; left: 0px; top: 0px;">
  <div style="width: 100%; height: 100%; position: relative; left: 0px; top: 0px; padding: 0px; margin: 0px">
    <div style="width: 100%; height: 100%; position: absolute; left: 0px; top: 0px; padding: 0px; margin: 0px; min-width: 100vw; min-height: 100vh"> </div>
  </div>
</div>


推荐阅读