聚焦浮动文本输入框时右侧显示Font Awesome关闭图标实现求助
实现聚焦输入框显示Font Awesome关闭图标
嘿,这需求很好搞定!结合你现有的浮动输入框代码,我们只需要调整HTML结构、补充CSS样式,再加一点点JS逻辑就能实现。下面是具体步骤:
1. 调整HTML结构
首先把Font Awesome的关闭图标加到你的浮动输入框容器里,和输入框、浮动标签同级就行:
<div class="floatInput"> <input type="text" id="targetInput" placeholder=" " /> <label class="floating-label">请输入内容</label> <!-- 新增的关闭图标 --> <i class="fa fa-times-circle clear-icon" aria-hidden="true"></i> </div>
注意:给input加个空的placeholder是为了兼容not(:placeholder-shown)的浮动逻辑,如果你已经加了可以忽略~
2. 补充CSS样式
用:focus伪类控制图标的显示,同时给容器加相对定位让图标能正确定位:
/* 先给浮动输入框容器加相对定位 */ .floatInput { position: relative; margin: 2rem 0; /* 你原有的其他容器样式 */ } /* 关闭图标初始隐藏,设置定位和样式 */ .floatInput .clear-icon { position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: #666; cursor: pointer; display: none; /* 默认隐藏 */ font-size: 18px; } /* 输入框聚焦时显示图标 */ .floatInput>input:focus~.clear-icon { display: block; } /* 保留你原有的浮动标签样式 */ .floatInput>input:focus~.floating-label, .floatInput>input:not(:placeholder-shown)~.floating-label { top: -10px; font-size: 0.8rem; color: #2196F3; /* 你原有的其他浮动样式 */ }
3. 点击外部隐藏图标的JS逻辑
光靠CSS没法处理点击外部隐藏的情况,加几行JS就能搞定:
const input = document.getElementById('targetInput'); const clearIcon = document.querySelector('.floatInput .clear-icon'); // 监听页面点击事件 document.addEventListener('click', (e) => { // 如果点击的不是输入框也不是图标,就隐藏图标 if (!input.contains(e.target) && e.target !== clearIcon) { clearIcon.style.display = 'none'; } }); // 可选:给图标加清空输入框的功能 clearIcon.addEventListener('click', () => { input.value = ''; input.blur(); // 清空后让输入框失去焦点,图标自动隐藏 });
这样就完美实现啦:输入框聚焦时关闭图标自动显示,点击页面其他区域或者点击图标清空内容后,图标就会隐藏。
内容的提问来源于stack exchange,提问作者user2147423
相关产品推荐
相关产品推荐

