React:找出一个元素是否在另一个引用容器内

var myContainer: any = null;


<div id="container" ref={container => myContainer = container}>

 <p id="child" > test</p>

</div>

现在我想知道 event.target 是否在 ref 内。


document.addEventListener("click", function (event) {


      var target = event.target;


      if(target is inside myContainer){

        console.log("target is inside my container");

      }



  });


慕斯王
浏览 208回答 3
3回答

长风秋雁

您可以使用contains. 尝试这样的事情&nbsp; document.addEventListener("click", function (event) {&nbsp; &nbsp; &nbsp; var target = event.target;&nbsp; &nbsp; &nbsp; if(this.myContainer && this.myContainer.contains(target)){&nbsp; &nbsp; &nbsp; &nbsp; console.log("target is inside my container");&nbsp; &nbsp; &nbsp; }&nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript