点击输入框清除按钮active状态及输入框失焦清空的实现
解决方案
要实现你需要的两个功能,只需在现有JavaScript代码中添加两个事件监听器即可,以下是修改后的完整代码及说明:
修改后的完整代码
HTML
<div class="row selectors d-flex justify-content-center" id="rc-button-bar"> <div class="col-xs-6 col-sm-6 col-md-2 mb-2"> <button id="btn-25" class="btn-primary ce-button" data-value="25">25%</button> </div> <div class="col-xs-6 col-sm-6 col-md-2 mb-2"> <button id="btn-50" class="btn-primary ce-button" data-value="50">50%</button> </div> <div class="col-xs-6 col-sm-6 col-md-2 mb-2"> <button id="btn-85" class="btn-primary ce-button is-active" data-value="85">85%</button> </div> <div class="col-xs-6 col-sm-6 col-md-2 mb-2"> <button id="btn-100" class="btn-primary ce-button" data-value="100">100%</button> </div> <div class="col-sm-12 col-md-2 mb-2 d-flex align-items-center"> <input id="customPercent" class="numbers" type="text" placeholder="ex: 80"></input> <span>%</span> </div> </div>
CSS
.btn-primary.ce-button { width: 100%; height: 48px; padding: auto; border: 4px solid #0079c1; border-radius: 5px; background: transparent; color: #0079c1; font-weight: bold; cursor: pointer; } .btn-primary.ce-button:hover, .btn-primary.ce-button:active { background: #0079c1; border-radius: 5px; color: #ffffff; font-weight: bold; cursor: pointer !important; } .is-active { background: #0079c1 !important; border-radius: 5px !important; color: #ffffff !important; font-weight: bold !important; }
JavaScript
let btnContainer = document.getElementById("rc-button-bar"); let btns = btnContainer.getElementsByClassName("ce-button"); let input = document.getElementById("customPercent"); // 原有按钮切换active逻辑 for (var i = 0; i < btns.length; i++) { btns[i].addEventListener("click", function() { const activeBtn = document.querySelector('.is-active'); if (activeBtn) activeBtn.classList.remove('is-active'); this.classList.add('is-active'); }); } // 功能1:点击输入框时清除所有按钮的active状态 input.addEventListener('focus', function() { const activeBtn = document.querySelector('.is-active'); if (activeBtn) activeBtn.classList.remove('is-active'); }); // 功能2:输入框失焦时清空输入内容 input.addEventListener('blur', function() { this.value = ''; });
关键逻辑说明
点击输入框清除按钮active状态:
- 给输入框绑定
focus事件,当输入框获得焦点时,查找当前带有is-active类的按钮,移除该类即可取消所有按钮的激活状态。
- 给输入框绑定
输入框失焦清空内容:
- 给输入框绑定
blur事件,当输入框失去焦点时,直接将其value设置为空字符串,实现清空效果。
- 给输入框绑定
另外,对原有按钮点击逻辑做了微小优化:将三元表达式改为更易读的if判断,代码逻辑保持一致但可读性更强。
内容的提问来源于stack exchange,提问作者notAGoodDeveloper
相关产品推荐
相关产品推荐

