简体   繁体   English

单击香草javascript中的文档时如何关闭输入

[英]How to close input when click on document in vanilla javascript

I have created an input with a button that when I click on button, input show and remove.我创建了一个带有按钮的输入,当我单击按钮时,输入显示并删除。 But I also want to remove input when I click on DOM, and I know I should set addEventListeners to DOM.但是我也想在单击 DOM 时删除输入,并且我知道我应该将addEventListeners设置为 DOM。 But I don't know what function I should use.但我不知道我应该使用什么 function 。

在此处输入图像描述

在此处输入图像描述

//Html
<div class="search">
  <input type="text" class="input" placeholder="Search . . ." />
  <button class="btn">
    <i class="fas fa-search"></i>
  </button>
</div>

//Js
const searchSection = document.querySelector(".search");
const input = document.querySelector(".input");
const searchBtn = document.querySelector(".btn");

searchBtn.addEventListener("click", () => {
 searchSection.classList.toggle("active");
 input.focus();
}); 

The vanilla JS way to listen for click events is listen for all clicks on the document, and then check if the clicked element has the selector you care about. vanilla JS 监听点击事件的方式是监听文档上的所有点击,然后检查被点击的元素是否有你关心的选择器。

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

    // If the clicked element doesn't have the right selector, bail
    if (!event.target.matches('.click-me')) return;

    // Don't follow the link
    event.preventDefault();

    // Log the clicked element in the console
    console.log(event.target);

}, false);

This approach is called event delegation, and it works by taking advantage of something called event bubbling.这种方法称为事件委托,它通过利用称为事件冒泡的东西来工作。

You can read more on Listening for click events with vanilla JavaScript您可以阅读有关使用 vanilla JavaScript 监听点击事件的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM