如何在Typescript中使用EventTarget

bla*_*ing 2 dom-events typescript

嘿,我是Typescript的新手,在实现Event Target时遇到了一些麻烦。

Javascript中使用的event.target.matches的打字稿等效项是什么?

示例代码:

function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (!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');
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*sky 5

您需要将(类型断言)转换event.target为类似的东西,HTMLElement以提供对HTMLElement诸如的方法的访问matches()。如果没有event.target强制类型转换,则键入,EventTarget这就是为什么您看不到matches()或无法使用其他HTMLElement方法的原因。

if (!(<HTMLElement> event.target).matches('.dropbtn')) { }
Run Code Online (Sandbox Code Playgroud)

这是一个实际的例子

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');
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

根据@WsCandy的建议,您还可以使用as以下替代方法:

window.onclick = function(event) {
      const target = event.target as HTMLElement;
      if (!target.matches('.dropbtn')) {
Run Code Online (Sandbox Code Playgroud)