HTML5 has made many enhancements to Web Form, such as input's new type type, Form Validation, etc. Placeholder is another attribute added to HTML5. When input or textarea sets this attribute, the content of this value will be displayed in the text box as a gray-word prompt. When the text box gains focus, the prompt text disappears. In the past, to achieve this effect, JavaScript was used to control it:
Since placeholder is a new attribute, only a few browsers currently support it. How to detect whether the browser supports it? (More HTML5/CSS3 feature detection can be accessed)
function hasPlaceholderSupport() {
return 'placeholder' in document.createElement('input');
}
The default prompt text is gray, and the text style can be changed through CSS:
/* all */::-webkit-input-placeholder { color:#f00; }input:-moz-placeholder { color:#f00; } /* individual: webkit */#field2::-webkit-input-placeholder { color:#00f; }#field3::-webkit-input-placeholder { color:#090; background:lightgreen; text-transform:uppercase; }#field4::-webkit-input-placeholder { font-style:italic; text-decoration:overline; letter-spacing:3px; color:#999; } /* individual: mozilla */#field2:-moz-placeholder { color:#00f; }#field3:-moz-placeholder { color:#090; background:lightgreen; text-transform:uppercase; }#field4:-moz-placeholder { font-style:italic; text-decoration:overline; letter-spacing:3px; color:#999; }Compatible with other browsers that do not support placeholder:
var PlaceHolder = {
_support: (function() {
return 'placeholder' in document.createElement('input');
})(),
//The style of the prompt text needs to be defined in other locations on the page
className: 'abc',
init: function() {
if (!PlaceHolder._support) {
//The textarea has not been processed, add what you need to do
var inputs = document.getElementsByTagName('input');
PlaceHolder.create(inputs);
}
},
create: function(inputs) {
var input;
if (!inputs.length) {
inputs = [inputs];
}
for (var i = 0, length = inputs.length; i <length; i++) {
input = inputs[i];
if (!PlaceHolder._support && input.attributes && input.attributes.placeholder) {
PlaceHolder._setValue(input);
input.addEventListener('focus', function(e) {
if (this.value === this.attributes.placeholder.nodeValue) {
this.value = '';
this.className = '';
}
}, false);
input.addEventListener('blur', function(e) {
if (this.value === '') {
PlaceHolder._setValue(this);
}
}, false);
}
}
},
_setValue: function(input) {
input.value = input.attributes.placeholder.nodeValue;
input.className = PlaceHolder.className;
}
};
//Initialize all inputs when page initialization
//PlaceHolder.init();
//or set an element separately
//PlaceHolder.create(document.getElementById('t1'));