2013-07-19 136 views
-4

我尝试使用placeholder编辑div。但我想在此div中没有​​文本时自动占位符设置。如果可编辑div没有设置占位符的文本

其实我正在使用contentEditable='true';这个元素在div上。而我用jQuery来处理占位符到这个函数。 `

 $('div').on('activate', 
     function() { 
     $(this).empty(); 
     var range, sel; 
    if ((sel = document.selection) && document.body.createTextRange){ 
    range = document.body.createTextRange(); 
    range.moveToElementText(this); 
    range.select();} });  


    $('div').focus(function() { 
    if (this.hasChildNodes() && document.createRange && window.getSelection) { 

    $(this).empty(); 
    var range, sel; 
    range = document.createRange(); 
    range.selectNodeContents(this); 
    sel = window.getSelection(); 
    sel.removeAllRanges(); 
    sel.addRange(range); 
}}); 

`

+0

我应该张贴一些代码工作,你有什么标记?你想要做什么? – Mangiucugna

回答

1

你可以这样做:

<div contenteditable="true" id="editDiv">Placeholer</div> 

jQuery的

var placeholder = "Placeholder"; //Change this to your placeholder text 
$("#editDiv").focus(function() { 
    if ($(this).text() == placeholder) { 
     $(this).text(""); 
    } 
}).focusout(function() { 
    if (!$(this).text().length) { 
     $(this).text(placeholder); 
    } 
}); 
+0

这是不正确的事情不符合我的要求。 –

-1

这不是在问题的措辞很清楚,但它听起来像你想一个text area

+0

我不想要我知道的文字区域。 –

0

你的问题很模糊,但我会尽我所能,给你某种维修解决方案:

HTML:

<div id="editableDiv"> 
    <textarea id="editText" placeholder="This is my placeholder"></textarea> 
</div> 

CSS:

#editableDiv { 
    width: 400px; 
    height: 200px; 
} 

#editText { 
    width: 100%; 
    height: 100%; 
} 

很抱歉,如果它不是你要找的东西,但这是我所能提供的大量信息所能做到的最好的。

http://jsfiddle.net/LB7cp/

7

你coud尝试使用CSS与伪:empty:before和数据属性。 http://codepen.io/gcyrillus/pen/hzLIE

div:empty:before { 
    content:attr(data-placeholder); 
    color:gray 
} 
<div contenteditable="true" data-placeholder="You can insert & edit content here."></div> 

应该在几个浏览器

相关问题