我跟着一个关于如何为div [contenteditable]创建占位符的SO问题。
我的代码如下:http://jsfiddle.net/sdxjgkzm/
$('div[data-placeholder]').on 'keydown input', ->
if (this.textContent)
this.dataset.divPlaceholderContent = 'true'
else
delete(this.dataset.divPlaceholderContent)
不幸的是,问题在于,您可以看到标准输入的占位符一直保持到您开始输入为止,而只要您在内部点击就会消失该信号。
我该如何解决这个问题?
答案 0 :(得分:2)
稍微改变你的HTML,然后使用下面的css:使用placeholder
而不是data-placeholder
,即没有数据属性。
input,div {
border: 1px black solid;
margin-top: 20px;
}
[contenteditable=true]:empty:before {
content: attr(placeholder);
}
<input placeholder="test"/>
<div contenteditable='true' placeholder="test"></div>
答案 1 :(得分:1)
检查一下,仅限CSS :)
Placeholder support for contentEditable elements, without JavaScript
更新小提琴:enter link description here
您只需要添加以下CSS:
[contenteditable=true]:empty:before {
content: attr(placeholder);
display: block; /* For Firefox */
}
/* General Styling for Demo only */
div[contenteditable=true] {
border: 1px dashed #AAA;
width: 290px;
padding: 5px;
}
pre {
background: #EEE;
padding: 5px;
width: 290px;
}
<h3>Placeholder support for contentEditable elements,<br>without JavaScript!</h3>
<h5>Demo:</h5>
<div contenteditable="true" placeholder="Enter text here..."></div>
<p>All you need is to add the following CSS:</p>
<pre>
[contenteditable=true]:empty:before {
content: attr(placeholder);
display: block; /* For Firefox */
}
</pre>
<h5>Notes</h5>
<ul>
<li>Can add a different style than actual text like opacity, italic, etc</li>
<li>If your html needs to be 100% compliant, you can replace "placeholder" for "data-placeholder" on both files</li>
<li>Chrome will add <br />'s inside contentEditable elements in some cases, breaking the :empty check. Can be fixed with a bit of JavaScript.</li>
</ul>
<i>By Ariel Flesler</i>