首页 > 解决方案 > 如何根据使用 CSS 对嵌套输入的关注来更改分隔 div 的颜色?

问题描述

结构与此类似:

<div>
    <div id="selected">
        <div id="inBetweenDiv">
            <input id="action"></input>
        </div>
    </div>
    <div id="changeThis"></div>
</div>

我想在输入元素的焦点上更改#changeThis 的背景。

标签: htmlcss

解决方案


在纯 CSS 中,您可以使用:focus-within伪类

#selected:focus-within ~ #changeThis {
   background: yellowgreen
}
<div>
    <div id="selected">
        <div id="inBetweenDiv">
            <input id="action" />
        </div>
    </div>
    <div id="changeThis">Change this</div>
</div>


否则你可以通过 JS 做同样的事情,如果你需要支持旧的浏览器,例如

var input = document.getElementById('action');
var ct    = document.getElementById('changeThis');

input.addEventListener('focus', () => { ct.classList.add('focus'); });
input.addEventListener('blur',  () => { ct.classList.remove('focus'); });

在 CSS 中——假设#changeThis已经应用了默认背景——你需要使用更具体的选择器,比如

#changeThis.focus {
   background: yellowgreen;
}

推荐阅读