Shadowroot:没有获得事件监听器的正确目标
我有一个带有模态的网页,在 Shadowroot 下有一个自定义下拉菜单,如下所示:
<div id="main">
#shadow-root
<div class="modal fade in" id="sample-modal">
<div class="modal-dialog modal-xl" role="dialog" aria-hidden="true">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title" style="font-size:0.85rem" id="download-modal-label">Modal Title</h6>
</div>
<form onsubmit="return false;">
<div class="modal-body" id="modal-body" style="overflow: inherit !important">
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
<a href="#about">About</a>
<a href="#base">Base</a>
<a href="#blog">Blog</a>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
为此,我想添加一个事件侦听器,如果我单击下拉菜单之外的任何位置,我会隐藏下拉 div。为此,我添加了事件侦听器,如下所示:
let root = document.getElementById("main").shadowRoot;
$(root).on("click", function(e) {
var clickedOn=$(e.target);
});
但这似乎根本不起作用。我尝试将单击事件侦听器附加到文档,以检查事件目标,如下所示:
$(document).on("click", function(e) {
var clickedOn=$(e.target);
});
此事件侦听器被触发,但目标元素“e”显示为
I have a webpage with a modal with a custom dropdown under a shadowroot as follows:
<div id="main">
#shadow-root
<div class="modal fade in" id="sample-modal">
<div class="modal-dialog modal-xl" role="dialog" aria-hidden="true">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title" style="font-size:0.85rem" id="download-modal-label">Modal Title</h6>
</div>
<form onsubmit="return false;">
<div class="modal-body" id="modal-body" style="overflow: inherit !important">
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
<a href="#about">About</a>
<a href="#base">Base</a>
<a href="#blog">Blog</a>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
For this, I want to add an event listener where if I click anywhere besides the dropdown, I hide the dropdown div. For this, I added the event listener as follows:
let root = document.getElementById("main").shadowRoot;
$(root).on("click", function(e) {
var clickedOn=$(e.target);
});
But this doesn't seem to work at all. I tried attaching the click event listener to the document, to check the event target as follows:
$(document).on("click", function(e) {
var clickedOn=$(e.target);
});
This event listener is triggered, but the target element 'e' it shown as the <div id="main">
irrespective of if I click on any element including the dropdown element under the modal. How do I add the event listener where I get the correct element under the shadowRoot which was clicked on using the 'click' event listener?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用addEventListener
use
addEventListener