我有以下内容: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>
问题是 <h1>
居中,但占位符插入符未居中(直到您开始键入)。插入符号在左侧,我该如何更改它?
最佳答案
这不是一个理想的解决方案,但我们可以通过应用 padding-left
来伪造效果的 50%
到 :empty
元素使光标出现在中间。
然后使用绝对定位和负值 translateX
将占位符(伪元素)居中对齐变换函数。
* {
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>
唯一剩下的问题——正如在 OP 提供的代码中所见——是在 Firefox 上,一个空的 <br>
元素附加到 contentEditable
导致 :empty
的元素伪类不再匹配元素。因此占位符不会被恢复。
然而,由于问题是关于光标的位置,我认为这种行为对 OP 来说很好。
关于javascript - 使占位符插入符在 contentEditable 元素中居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29288975/