Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 41 期W3C标准-JavaScript-DOM):点击空白处检测 #44

Open
wingmeng opened this issue Jun 25, 2019 · 0 comments
Open

第 41 期W3C标准-JavaScript-DOM):点击空白处检测 #44

wingmeng opened this issue Jun 25, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented Jun 25, 2019

题目:

<div id="box">
  <h2>酱油君1</h2>
  <p>酱油君2</p>
  <div>
    <input type="text">
    <button>按钮</button>
  </div>
</div>
#box {
  position: absolute;
  top: 20%;
  left: 40%;
  width: 300px;
  padding: 1em;
  background: #f5f5f5;
  border: 1px solid #ccc;
}

请编写一个方法,实现点击 #box(含内部元素)时,浏览器控制台输出 "inner",点击 #box 外部空白处时输出 "outer"


参考答案:

const box = document.getElementById('box');

window.addEventListener('click', e => {
  let elm = e.target;

  if (elm === box || box.contains(elm)) {  // 自身或内部元素
    console.log('inner');
  } else {
    console.log('outter');
  }
});

Node.contains 方法

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant