你需要投(
type assertion
)
event.target
就像
HTMLElement
提供访问
HTMLElement公司
方法,例如
matches()
.没有演员,
事件目标
键入为
EventTarget
这就是为什么你没有看到
匹配项()
或其他
HTMLElement公司
方法可用。
if (!(<HTMLElement> event.target).matches('.dropbtn')) { }
这是一个
example
正在运行。
window.onclick = function(event) {
if (!(<HTMLElement> event.target).matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
根据@WsCandy的建议,您也可以使用
as
作为替代方案:
window.onclick = function(event) {
const target = event.target as HTMLElement;
if (!target.matches('.dropbtn')) {