【发布时间】:2012-03-03 21:43:02
【问题描述】:
我有“contenteditable”的 div 元素。我想为它设置一个水印,这样当用户尝试在 div 中写一些东西时,水印就会消失。
我尝试了一些水印 jQuery 插件,都适用于输入,textarea。对 contenteditable div 实现这个功能的方法是什么?
【问题讨论】:
标签: javascript jquery html contenteditable
我有“contenteditable”的 div 元素。我想为它设置一个水印,这样当用户尝试在 div 中写一些东西时,水印就会消失。
我尝试了一些水印 jQuery 插件,都适用于输入,textarea。对 contenteditable div 实现这个功能的方法是什么?
【问题讨论】:
标签: javascript jquery html contenteditable
如果您所说的“水印”是指占位符效果,那么这个概念应该相当简单:
var mark = 'Watermark',
edited = false;
$('[contenteditable]').focus(function() {
if(!edited) {
$(this).empty();
}
}).blur(function() {
if(!$(this).html()) {
$(this).html(mark);
}
}).keyup(function() {
edited = true;
}).text(mark);
【讨论】:
mark 相同的文本,那么它就是一个问题。
$('[contenteditable]').bind("focus keydown",function() { ...//same as your code
.empty() 而不是.html("")
这是我对另一个问题的回答:
它使用 jQuery 和 CSS3 的组合。 与 html5 占位符属性完全相同!。
HTML:
<div class="placeholder" contenteditable="true"></div>
CSS3:
.placeholder:after {
content: "Your placeholder"; /* this is where you assign the place holder */
position: absolute;
top: 10px;
color: #a9a9a9;
}
jQuery:
$('.placeholder').on('input', function(){
if ($(this).text().length > 0) {
$(this).removeClass('placeholder');
} else {
$(this).addClass('placeholder');
}
});
【讨论】:
我是这样解决的:
div[contenteditable]:empty:before {
content: '-';
}
div[contenteditable]:focus:before {
color: transparent;
}
【讨论】: