CSS3 - 如何在textareas和Chrome中的输入中设置所选文本的样式?

时间:2011-12-08 22:10:39

标签: css google-chrome css3 webkit

编辑:正如@geca在评论中指出的那样,这是一个已知的WebKit bug。我们希望很快得到修复!

::selection伪元素允许对所选文本进行样式设置。这可以按预期工作,但不适用于Google Chrome 15中的textareas和输入。 (我不确定它是否是webkit或chrome问题,因为我无法在Linux上使用Safari。)

以下是展示此问题的jsfiddle:http://jsfiddle.net/J5N7K/2/ pargraph中选定的文本按其应有的样式设置。 textarea中的选定文本和输入不是。 (但它在Firefox上。)

我做错了什么或者现在不能在Chrome上设置样式?

3 个答案:

答案 0 :(得分:8)

<div>contenteditable选项吗?函数只为大多数事情列出<textarea>

演示:http://jsfiddle.net/ThinkingStiff/FcCgA/

HTML:

<textarea>&lt;textarea&gt; Doesn't highlight properly in Chrome.</textarea><br />
<input value="&lt;input&gt; Doesn't highlight properly in Chrome." />
<p>&lt;p&gt; Highlights just fine in Chrome!</p>
<div id="div-textarea" contenteditable>&lt;div contenteditable&gt; Highlights just fine in Chrome!</div>

CSS:

textarea, input, p, div {
    width: 400px;
}

#div-textarea {
    -webkit-appearance: textarea;
    height: 32px;
    overflow: auto;
    resize: both;
}

::selection {
    background-color: black;
    color: white;
}

输出(Chrome):

enter image description here

答案 1 :(得分:5)

这是一个众所周知的 WebKit bug 。对不起,到目前为止没有解决办法:)

更新:WebKit错误已于2014年10月13日修复。

答案 2 :(得分:0)

有没有机会不使用CSS伪元素,你可以使用一些jQuery。

看看这个http://jsfiddle.net/J5N7K/6/

如果你不明白jQuery可以随意询问它。