代码之家  ›  专栏  ›  技术社区  ›  blazing

如何在Typescript中使用EventTarget

  •  5
  • blazing  · 技术社区  · 7 年前

    嘿,我是Typescript新手,在实现事件目标时遇到了一些问题。

    事件的typescript等效于什么。目标Javascript中使用的匹配项?

    示例代码:

    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');
          }
        }
      }
    }
    
    1 回复  |  直到 7 年前
        1
  •  11
  •   Zoe - Save the data dump 张群峰    6 年前

    你需要投( 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')) {
    
    推荐文章