【问题标题】:CSS3 - change parent's pseudo-element's color on focus?CSS3 - 更改父级伪元素的焦点颜色?
【发布时间】:2013-12-05 00:03:20
【问题描述】:

这个非常棘手,我很确定它无法用普通的 CSS3 实现(很容易用 jQuery,但我试图避免这种情况)。也许一些黑客?我需要它与跨浏览器兼容(IE7+ 及其他)。

我有一个 :before 用于 .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/

【问题讨论】:

  • IE7 不完全支持伪选择器,例如:before,无论如何您都必须使用一些 javacript。 Source
  • @Zeaklous,IE8+ 怎么样?有什么想法吗?
  • 我发布了一个最接近 IE8+ 的纯 CSS 的答案。有什么反馈吗?

标签: css colors pseudo-element


【解决方案1】:

如果您只提供 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

可以不使用容器元素,但我不建议这样做,因为它涉及使用 ID 或 nth-child 疯狂并补偿边距和任何其他位置变化。 Demo of the ID approach。如果您的其他元素在页面上移动,这也会失败,例如由于窗口太小而重新定位

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 2014-04-19
    • 1970-01-01
    • 2013-02-27
    相关资源
    最近更新 更多