这个非常棘手,我很确定它无法用纯 CSS3 实现(使用 jQuery 很容易,但我正在努力避免这种情况)。也许一些黑客?我需要它是跨浏览器兼容的(IE7+ 及其他)。
我有一个 .wrapper 的 :before 伪元素。我希望它在 .wrapper child(输入)为:focus 时改变颜色。有什么想法吗?
这是 HTML:
<p class="wrapper"><input type="text" /></p>
和 CSS:
body {
background: #eee;
}
.wrapper input[type="text"] {
position: relative;
padding: 10px 30px;
}
input { font-family: 'FontAwesome'; background: #333; border: solid 1px #000; }
.wrapper {
position: relative;
}
.wrapper:before {
font-family: 'FontAwesome';
color: #fff;
position: absolute;
top: 13px;
left: 15px;
content: "\f007";
z-index: 999;
}
input:focus {
border: solid 1px #fff;
outline: 0;
color: #333;
background: #fff;
}
我想到的最好的事情是:
.wrapper:before:hover {
color: #333;
}
但是当用户只是将鼠标悬停在输入上而不点击它时,这很糟糕。
和 jsfiddle 一起玩:http://jsfiddle.net/8kEgz/2/
最佳答案
如果您只支持 IE8+,您可以稍微更改 HTML 以获得您想要的效果。我建议使用容器,但下面是非容器版本。诀窍是将 input
作为 p
/* HTML */
<div class='contain'>
<input type="text"/>
<p class="wrapper"></p>
</div>
/* CSS */
body { background: #eee; }
.contain input[type="text"] {
position: relative;
padding: 10px 30px;
}
input { font-family: 'FontAwesome'; background: #333; border: solid 1px #000; }
.wrapper:before {
font-family: 'FontAwesome';
color: #fff;
position: absolute;
top: 20px;
left: 20px;
content: "\f007";
z-index: 1;
}
input:focus {
border: solid 1px #fff;
outline: 0;
color: #333;
background: #fff;
}
input:focus + .wrapper:before { color:#333; }
没有容器元素也是可能的,但我不推荐它,因为它涉及使用 ID 或 nth-child
疯狂和补偿边距和任何其他位置变化。 Demo of the ID approach .如果您的其他元素在页面上四处移动,这也会失败,例如重新定位,因为窗口太小了
关于CSS3 - 在焦点上更改父元素的伪元素颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20105371/