如何点击search-icon类div后隐藏指定HTML文本元素?
点击搜索图标隐藏引导文本的实现方案
需求说明
点击class为search-icon的div元素时,隐藏id为intro下的那段引导文本:<p>Simply click on the … and type the name of where you would like to visit</p>。
你的HTML结构
<div id="intro"> <p>Simply click on the <i class="fas fa-search"></i> and type the name of where you would like to visit</p> <div class="search-box"> <input id="searchBox" type="text" placeholder="Search your location"> <div class="search-icon"> <i class="fas fa-search"></i> </div> <div class="cancel-icon"> <i class="fas fa-times"></i> </div> <div class="search-data"></div> </div> </div>
可行的JavaScript实现方案
方案一:直接设置元素样式隐藏
这种方法简单直接,点击后直接把目标p标签的display设为none:
// 获取搜索图标元素 const searchIcon = document.querySelector('.search-icon'); // 获取intro下的p标签 const introText = document.querySelector('#intro p'); // 绑定点击事件 searchIcon.addEventListener('click', function() { introText.style.display = 'none'; });
方案二:通过CSS类控制(推荐,更灵活)
先在CSS里定义一个隐藏类:
.hidden { display: none !important; }
然后用JavaScript给目标p标签添加这个类:
const searchIcon = document.querySelector('.search-icon'); const introText = document.querySelector('#intro p'); searchIcon.addEventListener('click', function() { introText.classList.add('hidden'); });
如果之后需要重新显示这段文本,只需要调用introText.classList.remove('hidden')即可。
方案三:兼容旧浏览器的写法(如需支持IE8及以下)
var searchIcon = document.getElementsByClassName('search-icon')[0]; var introText = document.getElementById('intro').getElementsByTagName('p')[0]; searchIcon.onclick = function() { introText.style.display = 'none'; };
内容的提问来源于stack exchange,提问作者moni_maj89
相关产品推荐
相关产品推荐

