Html 是否可以在div标签中添加占位符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20300138/
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
Is it possible to add placeholder in div tag
提问by user123
I would like to display some text to the user when my div
element is empty.
当我的div
元素为空时,我想向用户显示一些文本。
I have tried adding a placeholderattribute to my div
but the text is not being displayed.
我曾尝试向我添加占位符属性,div
但未显示文本。
<div placeholder="Enter the text"> </div>
How can I display a message when my div
element is empty?
当我的div
元素为空时如何显示消息?
回答by Joke_Sense10
回答by G-Cyrillus
i have already answered to such a question here with this test : http://codepen.io/gcyrillus/pen/hzLIE
我已经在这个测试中回答了这样一个问题:http: //codepen.io/gcyrillus/pen/hzLIE
div:empty:before {
content:attr(data-placeholder);
color:gray
}
回答by matt.
This can also be achieved without the use of the contentEditableattribute, using plain CSS.
这也可以在不使用contentEditable属性的情况下使用纯 CSS 实现。
Using the :emptypseudo-class along with the ::beforepseudo-element you can add a placeholder to an empty element.
使用:empty伪类和::before伪元素,您可以向空元素添加占位符。
The following example provides a fallback placeholder for div
elements that do not have a data-placeholder
attribute defined.
以下示例为未定义属性的div
元素提供了备用占位符data-placeholder
。
Example:
例子:
div:empty::before {
color: grey;
}
div[data-placeholder]:not([data-placeholder=""]):empty::before {
content: attr(data-placeholder);
}
div:empty::before {
content: 'fallback placeholder';
}
<div data-placeholder='data- placeholder'></div>
<br>
<div></div>
回答by SquareCat
Assuming what you really want to do is to have the user input some text and show him some placeholder in the input field, this is what you can use:
假设您真正想要做的是让用户输入一些文本并在输入字段中向他显示一些占位符,这就是您可以使用的:
<input type="text" value="Enter the text" onfocus="if(this.value=='Enter the text'){this.value='';}" onblur="if(this.value==''){this.value='Enter the text';}" />
Of course you can wrap the input in a div.
当然,您可以将输入包装在 div 中。
<div><input [...] /></div>
You can see this in action here
你可以在这里看到这个