正在向我的网页添加搜索栏,在较小的屏幕上,导航栏上有搜索图标,切换后它可以在导航栏正下方(主要内容中的第一个)启用搜索栏可见性。在此之前,切换导航栏中的搜索图标会使搜索栏在导航栏正下方可见,该导航栏位于主要内容中。单击搜索栏(输入字段)外部后,搜索栏可见性设置为 none 。现在这是我遇到的问题!当我切换搜索图标时,搜索栏会出现,因此任何在搜索栏之外的点击都会使主要内容中的所有内容消失,我只希望搜索栏可见性不包括其余内容。下面是我的引导代码
** Bootstrap codes**
<!------------------------------Main Content-------------------------->
<!-- Button trigger search panel . -->
<div class="container">
<form action="GET" id="searchPanel">
<div class="input-group mb-3 d-flex rounded-4" style="width:100%;" id="input">
<div class="input-group-prepend">
<span class="input-group-text d-block mx-auto"><i class="fa-solid fa-magnifying-glass" id="searchIcon"></i></span>
</div>
<input type="text" class="form-control" placeholder="Search for....">
<button type="submit" class="btn btn-outline-success ">Search</button>
</div>
</form>
</div>
JavaScript 实现
document.addEventListener('DOMContentLoaded', () => {
const searchIcon= document.getElementById('search');
const searchBar = document.getElementById('searchPanel');
const searchInput = document.getElementById('input')
//Toggle search bar visibility
searchIcon.addEventListener('click', () => {
if(window.innerWidth < 992) {
searchBar.style.display = (searchBar.style.display === 'block') ? 'none' : 'block'
}
});
//Hide search bar clicking outside appeared search bar
document.addEventListener('click', (e) => {
const clickInside = searchIcon.contains(e.target) || searchBar.contains(e.target);
if(!clickInside) {
searchBar.style.display = 'none';
}
});
})
你可以使用下面的类似方法,我只是给你一个想法,但你必须实现它。
// when a click has occurred then this event will be triggered
window.addEventListener(
"click",
(e) => {
// I use div but you should use a container or hero section or another one that holds your entire elements like a section
if (e.target.matches("div")) {
// make display none or disable here...
// I mean your next logic will be here..
}
},
true
);