如何使用 event.target.matches 来匹配 div 元素

Sah*_*and 4 html javascript jquery dom

<!DOCTYPE html>
<html>
    <head>
        <style>
            .dropdown-content a{
                display: block;
                background-color: blue;
            }
        </style>
    </head>
    <body>
        <div class="dropdown-content">
            <a>1</a>
            <a>2</a>
        </div>
        <script>
            window.onclick = function(event){
                if(!event.target.matches('.dropdown-content')){
                    alert("foo");
                }   
            };
        </script>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我试图alert(foo);仅在我们没有点击div正文中标签内的任何内容时才执行。不幸的是,无论我点击哪里,它都会执行。为什么?

Dur*_*rga 10

window.onclick = function(event){
 if (document.getElementsByClassName('dropdown-content')[0].contains(event.target)){
    // inside
  } else{
    // outside
    alert('foo');
  }
};
Run Code Online (Sandbox Code Playgroud)
.dropdown-content a{
    display: block;
    background-color: blue;
}
Run Code Online (Sandbox Code Playgroud)
<div class="dropdown-content">
  <a>1</a>
  <a>2</a>
</div>
Run Code Online (Sandbox Code Playgroud)

获取您的元素并使用contains来检查点击是在内部还是外部。如果在外面,则警报。

matches无法正常工作,因为您正在单击a没有.dropdown-content标签的标签。所以每次值都为假。而它alert('foo')