在contentEditable元素中居中位置符号 [英] Centering the placeholder caret in contentEditable element
问题描述
我有以下内容: http://jsfiddle.net/mb76koj3/ 。
[contentEditable = true]:empty :: before {content:attr(data-ph);颜色:#CCC; text-align:center;} h1 {text-align:center;}
p>
问题是< h1>
居中,但占位符脱字符不居中)。
不是一个理想的解决方案,但我们可以通过将 padding-left
应用到:empty
的 50%>元素,使光标出现在中间。
然后使用绝对定位对齐占位符(伪元素),并使用负值 translateX
转换函数。
* {margin:0; padding:0;} @ - moz-document url-prefix(){/ * CSS Hack修复光标在FF上的位置* / [contentEditable = true]:empty {padding-top:1em; padding-bottom:.25em; -moz-box-sizing:content-box; }} [contentEditable = true]:empty {padding-left:50%; text-align:left; / *修复IE * /}上的问题[contentEditable = true]:empty :: before {content:attr(data-ph);颜色:#CCC; position:absolute; top:0;左:50%; -webkit-transform:translateX(-50%); -moz-transform:translateX(-50%); -ms-transform:translateX(-50%); -o-transform:translateX(-50%); transform:translateX(-50%);} h1 {text-align:center; position:relative;}
< h1 contenteditable = data-ph =Name>< / h1>
在OP的提供的代码中可以看到的唯一问题是在Firefox上,一个空的< br>
元素附加到 contentEditable
元素导致:empty
伪类不再匹配元素。因此,占位符将不会被恢复。
然而,由于问题是关于光标的位置,我认为这种行为对于OP很好。
I have the following: http://jsfiddle.net/mb76koj3/.
[contentEditable=true]:empty::before{
content:attr(data-ph);
color: #CCC;
text-align: center;
}
h1 {
text-align: center;
}
<h1 contenteditable="true" data-ph="Name"></h1>
The problem is the <h1>
is centered, but the placeholder caret isn't centered (until you start typing). The caret is on the left side, how can I change this?
Not an ideal solution but we can fake the effect by applying a padding-left
of 50%
to the :empty
element to make the cursor appear at the middle.
And then align the placeholder (the pseudo-element) at the middle by using absolute positioning and a negative value of translateX
transform function.
* {
margin: 0;
padding: 0;
}
@-moz-document url-prefix() { /* CSS Hack to fix the position of cursor on FF */
[contentEditable=true]:empty {
padding-top: 1em;
padding-bottom: .25em;
-moz-box-sizing: content-box;
}
}
[contentEditable=true]:empty {
padding-left: 50%;
text-align: left; /* Fix the issue on IE */
}
[contentEditable=true]:empty::before{
content:attr(data-ph);
color: #CCC;
position: absolute;
top: 0;
left: 50%;
-webkit-transform: translateX(-50%);
-moz-transform: translateX(-50%);
-ms-transform: translateX(-50%);
-o-transform: translateX(-50%);
transform: translateX(-50%);
}
h1 {
text-align: center;
position: relative;
}
<h1 contenteditable="true" data-ph="Name"></h1>
The only problem that remains — as can be seen in the OP's provided code — is that on Firefox, an empty <br>
element is appended to contentEditable
elements which causes :empty
pseudo-class not matching the element anymore. Hence the placeholder won't be restored.
However since the question is about the position of the cursor, I assume this behavior is just fine for the OP.
这篇关于在contentEditable元素中居中位置符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!