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

如何在.input-search获取:focus状态时修改.search-box的背景色?

实现输入框聚焦时修改父容器背景色

方案1:原生CSS(推荐)

使用:focus-within伪类可以直接满足需求,它会匹配包含获焦元素的父容器:

.search-box:focus-within {
    background-color: #fff;
}

这个伪类的逻辑是:当.search-box内部的任意元素(此处就是.input-search)获得焦点时,自动给.search-box应用指定的背景色样式,完全契合你的需求。

方案2:JavaScript 兼容方案(适配旧浏览器)

如果需要兼容不支持:focus-within的旧浏览器(比如IE),可以通过监听焦点事件切换类来实现:

第一步:定义CSS激活状态样式

.search-box.active {
    background-color: #fff;
}

第二步:添加JS事件监听

const input = document.querySelector('.input-search');
const searchBox = input.parentElement;

// 输入框聚焦时给父容器添加激活类
input.addEventListener('focus', () => {
    searchBox.classList.add('active');
});

// 输入框失焦时移除激活类
input.addEventListener('blur', () => {
    searchBox.classList.remove('active');
});

内容的提问来源于stack exchange,提问作者Tom Caklos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 09:52:04