HTML/CSS Making a textbox with text that is grayed out, and disappears when I click to enter info, how?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
How do I make a textbox that has a grayed out content, and when I click on it to enter text, the grayed out portion, it disappears and allows me to enter the desired text?
Example:
A "First Name" text box. The words "First Name" are inside the text box grayed out, when I click, those words disappear and I write my name in it.
回答1:
This answer illustrates a pre-HTML5 approach. Please take a look at Psytronic's answer for a modern solution using the placeholder attribute.
HTML:
JavaScript:
function inputFocus(i) { if (i.value == i.defaultValue) { i.value = ""; i.style.color = "#000"; } } function inputBlur(i) { if (i.value == "") { i.value = i.defaultValue; i.style.color = "#888"; } }
回答2:
Chrome, Firefox, IE10 and Safari support the html5 placeholder attribute
In order to get a more cross browser solution you'll need to use some javascript, there are plenty of pre-made solutions out there, though I don't know any off the top of my head.
This is not supported with all browsers though (IE)
This may work:
Otherwise, if you are using jQuery, you can use .focus and .css to change the color.
回答4:
If you're targeting HTML5 only you can use:
For non HTML5 browsers, I would build upon Floern's answer by using jQuery and make the javascript non-obtrusive. I would also use a class to define the blurred properties.
$(document).ready(function () { //Set the initial blur (unless its highlighted by default) inputBlur($('#Comments')); $('#Comments').blur(function () { inputBlur(this); }); $('#Comments').focus(function () { inputFocus(this); }); })
Functions:
function inputFocus(i) { if (i.value == i.defaultValue) { i.value = ""; $(i).removeClass("blurredDefaultText"); } } function inputBlur(i) { if (i.value == "" || i.value == i.defaultValue) { i.value = i.defaultValue; $(i).addClass("blurredDefaultText"); } }
CSS:
.blurredDefaultText { color:#888 !important; }
回答5:
The shortest way is to directly add the below code as additional attributes in the input type that you want to change.