Html 如何为类似于文本字段的 DIV 创建“占位符”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16941360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a "placeholder" for DIV that act like textfield?
提问by user2399158
Div don't have a placeholder attribute
Div 没有占位符属性
<div id="editable" contentEditable="true"></div>
I want <Please your enter your Name>
to show in DIV when the User backspace the whole text in the DIV, or no text on inside, How can I do it?
<Please your enter your Name>
当用户退格 DIV 中的整个文本时,我想在 DIV 中显示,或者里面没有文本,我该怎么做?
回答by mrmoje
Here is a pure CSS only solution:-
这是一个纯 CSS 解决方案:-
<div contentEditable=true data-ph="My Placeholder String"></div>
<style>
[contentEditable=true]:empty:not(:focus):before{
content:attr(data-ph)
}
</style>
Here, we basically select all contentEditable
<divs>
that are empty & blurred. We then create a pseudo element before the CSS selection (the editable div) and fix our placeholder text (specified the data-ph
attribute) as its content.If you are targeting old school CSS2 browsers, change all occurrences of data-ph
to title
Correction.......the :empty
selector is not supported in IE version 8 and earlier.
在这里,我们基本上选择所有contentEditable
<divs>
空的和模糊的。然后我们在 CSS 选择(可编辑 div)之前创建一个伪元素,并将占位符文本(指定data-ph
属性)固定为其内容。如果您的目标是旧式 CSS2 浏览器,data-ph
title
请将所有出现的 更改为更正....... :empty
IE 8 及更早版本不支持选择器。
回答by MD Furkanul Islam
You can try this one !
你可以试试这个!
html:
html:
<div contentEditable=true data-text="Enter name here"></div>
css:
css:
[contentEditable=true]:empty:not(:focus):before{
content:attr(data-text) }
回答by acudars
in HTML
在 HTML 中
<div id="editable" contenteditable="true">
<p>Please your enter your Name</p>
</div>
in JavaScript
在 JavaScript 中
jQuery.fn.selectText = function(){
var doc = document;
var element = this[0];
console.log(this, element);
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
};
$("#editable").click(function() {
$("#editable").selectText();
});