https://jsfiddle.net/cp1ntk45/
我编写一个函数来替换原始的HTML占位持有人,然后我可以为占位符文字设计。
它可以与输入和文本元素一起使用,
问题如果目标是可满足的Div,单击一旦不集中精力,无法键入,就需要单击第二次以焦点...
如何仅单击一次,然后专注于
var placeholder = function(el) {
el.on('focusin', function() {
var val = $(this).text();
var placeholder = $(this).attr('data-placeholder');
if (val == placeholder) {
if ($(this).attr('data-empty') != 'false') {
$(this).text('');
}
}
});
el.on('focusout', function() {
var val = $(this).text();
var placeholder = $(this).attr('data-placeholder');
if (val == '') {
$(this).text(placeholder);
$(this).attr('data-empty', 'true');
} else {
$(this).attr('data-empty', 'false');
}
});
};
placeholder($('.textarea'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="textarea" contentEditable="true" data-placeholder="placeholder">placeholder</div>
您可以在您的contenteditable
元素上使用 CSS :empty
和:before
。
使用content: attr(data-placeholder);
,您可以 stamp 您想要的任何文本。
[contenteditable] {padding:12px; background:#eee; }
[data-placeholder]:empty:before{
content: attr(data-placeholder);
color: #888;
font-style: italic;
}
<div contenteditable data-placeholder="I'm a placeholder"></div>
通过单击和聚焦事件更改属性contentEditable
来解决此问题,如下面
el.on('click', function() {
$(this).attr('contentEditable', 'true');
$(this).focus();
});
el.on('focusout', function() {
$(this).attr('contentEditable', 'false');
});
https://stackoverflow.com/a/1599398/5593189