javascript - 如何将事件监听器绑定到特定的 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>
解决方案
这是因为您的 div 是空的,因此它不占用任何宽度或高度,因此在任何 div 上都不会触发任何事件。尝试向 div 添加一些内容。或者尝试设置任何最里面的 div 的min-height
和min-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>
推荐阅读
- c++ - 大型项目的 C++ 结构化单元测试
- python - Boost/Python 快速入门示例不构建 Windows 10
- php - FPDF多列:如何避免多单元拆分?
- android - Android中的位置传感器与运动传感器
- amazon-web-services - 如何获取 aws:lambda 函数的 Uri 作为文本?
- android - Listview 选择器中的第一项已启用
- machine-learning - 图像堆栈作为 CNN 的单一输入
- android - 如何集成 2 个 android 应用程序
- javascript - 如何查找用户的名字字母
- python - Python:并行化嵌套的 for 循环