猿问

在外部单击时如何隐藏输入?

我有一个用例,其中用户单击搜索图标,并显示输入。


我想这样做,以便在打开输入时,只要您在输入之外单击,它就会将其隐藏。


当然,我也想保持当前的切换状态。


试图找出一种使用普通JavaScript(而不是jQuery)的解决方案。


///////////// Nav - Search Functionality


// Toggle showing and not showing the input


const searchIcon = document.getElementById('search-icon');

const searchInput = document.getElementById('search-input');


searchIcon.addEventListener('click', function() {

  searchInput.classList.toggle('is-active');

  searchInput.classList.toggle('transform-is-active');

});

.is-active {

  display: block !important;

}


.is-hidden {

  display: none !important;

}


.transform-is-active {

  width: 200px !important;

}


#search-input {

  display: none;

  margin-right: 10px;

  transition: all 2s ease;

}


#search-icon {

  cursor: pointer;

}

<!--Search-->

<input id="search-input" class="input" type="text" placeholder="Search...">

<img id="search-icon" src="https://static.thenounproject.com/png/101791-200.png" alt="Search" tabindex="0" />


眼眸繁星
浏览 196回答 3
3回答

犯罪嫌疑人X

妳去 单击主体时(在图标外部),它将隐藏输入,并保留切换。const searchIcon = document.getElementById('search-icon');const searchInput = document.getElementById('search-input');searchInput.addEventListener('click', function(event){&nbsp; event.stopPropagation();});searchIcon.addEventListener('click', function(event) {&nbsp; searchInput.classList.toggle('is-active');&nbsp; searchInput.classList.toggle('transform-is-active');&nbsp; event.stopPropagation();});document.body.addEventListener('click', function(event) {&nbsp; searchInput.classList.remove('is-active');&nbsp; searchInput.classList.remove('transform-is-active');&nbsp; event.preventDefault();});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答