将占位符插入符号置于contentEditable元素中

Muh*_*mbi 10 html javascript css contenteditable

我有以下内容:http://jsfiddle.net/mb76koj3/.

[contentEditable=true]:empty::before{
  content:attr(data-ph);
  color: #CCC;
  text-align: center;
}

h1 {
  text-align: center;
}
Run Code Online (Sandbox Code Playgroud)
<h1 contenteditable="true" data-ph="Name"></h1>
Run Code Online (Sandbox Code Playgroud)

问题是<h1>居中,但占位符插入符号不居中(直到您开始键入).插入符号在左侧,我该如何更改?

Has*_*ami 10

不是一个理想的解决方案,但我们可以通过假施加影响padding-left50%: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;
}
Run Code Online (Sandbox Code Playgroud)
<h1 contenteditable="true" data-ph="Name"></h1>
Run Code Online (Sandbox Code Playgroud)

剩下的唯一问题 - 在OP提供的代码中可以看出 - 在Firefox上,一个空<br>元素被附加到contentEditable元素上,导致:empty伪类不再与元素匹配.因此占位符将不会被恢复.

但是,由于问题是关于光标的位置,我认为这种行为对OP来说很好.