Javascript Detect click event outside of div

前端 未结 10 941
孤城傲影
孤城傲影 2020-11-27 06:07

I have a div with id=\"content-area\", when a user clicks outside of this div, I would like to alert them to the fact that they clicked outside of it. How would I use JavaSc

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 06:27

    Bind the onClick-Event to an element that is outside your content area, e.g. the body. Then, inside the event, check whether the target is the content area or a direct or indirect child of the content area. If not, then alert.

    I made a function that checks whether it's a child or not. It returns true if the parent of a node is the searched parent. If not, then it checks whether it actually has a parent. If not, then it returns false. If it has a parent, but it's not the searched one, that it checks whether the parent's parent is the searched parent.

    function isChildOf(child, parent) {
        if (child.parentNode === parent) {
          return true;
        } else if (child.parentNode === null) {
          return false;
        } else {
          return isChildOf(child.parentNode, parent);
        }
    }
    

    Also check out the Live Example (content-area = gray)!

提交回复
热议问题