html - 如何根据使用 CSS 对嵌套输入的关注来更改分隔 div 的颜色?
问题描述
结构与此类似:
<div>
<div id="selected">
<div id="inBetweenDiv">
<input id="action"></input>
</div>
</div>
<div id="changeThis"></div>
</div>
我想在输入元素的焦点上更改#changeThis 的背景。
解决方案
在纯 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;
}
推荐阅读
- sql-server - 在 T-SQL 中对最多 2 列进行子查询的最佳方法是什么
- typo3 - 为来自 CLI 的图像生成 TYPO3 cropVariants
- python - 如何单击使用 Selenium 隐藏的下拉菜单?
- sql - 从逗号分隔的字符串中提取字符串的 SQL 查询
- python - 如何从列表中删除元素列表?
- postgresql - hasura:将空字符串视为空值
- reactjs - 使用 redux 在 next.js 中管理状态
- vuetify.js - 如何在 Vuetify v-select 中使用对象?
- php - 缺少 MySQLi 扩展
- amazon-web-services - 将标签添加到批处理作业并在 Cost Explorer 中查看它们