You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何点击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 &nbsp;<i class="fas fa-search"></i>&nbsp; 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 05:42:52