2013-11-20 148 views
0

这是一个非常棘手的问题,我很确定它无法用普通的CSS3实现(很容易用jQuery,但我试图避免这种情况)。也许有些黑客?我需要它是跨浏览器兼容的(IE7 + &其余)。CSS3 - 在焦点上更改父级的伪元素的颜色?

我有一个:在.wrapper伪元素之前。我想让它在改变颜色时.wrapper子(输入)是: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/

+0

IE7完全不支持伪选择器,比如':before',你将不得不使用一些javacript。 [来源](http://kimblim.dk/css-tests/selectors/) –

+0

@Zeaklous,那么IE8 +呢?有任何想法吗? – Wordpressor

+0

我发布了一个最接近您使用纯CSS达到IE8 +的答案。任何反馈? –

回答

0

如果你只提供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; } 

Demo here

有可能没有一个容器元素做长辈的兄弟姐妹,但我do't推荐它,因为它会涉及使用ID或nth-child疯狂并补偿利润率和其他任何位置变化。 Demo of the ID approach。如果你的其他元素在页面上移动,这也会失败,例如因为窗口太小而重新定位