我有一个用例,其中用户单击搜索图标,并显示输入。我想这样做,以便在打开输入时,只要您在输入之外单击,它就会将其隐藏。当然,我也想保持当前的切换状态。试图找出一种使用普通JavaScript(而不是jQuery)的解决方案。///////////// Nav - Search Functionality// Toggle showing and not showing the inputconst 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" />
3 回答
犯罪嫌疑人X
TA贡献2080条经验 获得超4个赞
妳去 单击主体时(在图标外部),它将隐藏输入,并保留切换。
const searchIcon = document.getElementById('search-icon');
const searchInput = document.getElementById('search-input');
searchInput.addEventListener('click', function(event){
event.stopPropagation();
});
searchIcon.addEventListener('click', function(event) {
searchInput.classList.toggle('is-active');
searchInput.classList.toggle('transform-is-active');
event.stopPropagation();
});
document.body.addEventListener('click', function(event) {
searchInput.classList.remove('is-active');
searchInput.classList.remove('transform-is-active');
event.preventDefault();
});
添加回答
举报
0/150
提交
取消