JSFiddle - React, Tailwind, and code Playground
by tu genhua
HTML
<h3>通过value方式模拟placeholder</h3>
<p>
<label for="username1">用户名:</label>
<input type="text" class="placeholderCls" placeholder="请输入用户名">
</p>
<p>
<label for="address1">地 址:</label>
<input type="text" class="placeholderCls" placeholder="请输入地址">
</p>
<p>
<label for="remarks1">备 注:</label>
<textarea placeholder="请输入备注" class="placeholderCls"></textarea>
</p>
JavaScript
/*
* JS placeholder
* IE6-IE9不支持HTML5中的placeholder
*/
function Placeholder(options) {
this.config = {
defaultColor: '#ccc',
curColor: '#333',
targetElem: '.placeholderCls'
};
this.init(options);
}
Placeholder.prototype = {
constructor:Placeholder,
init: function(options){
this.config = $.extend(this.config, options || {});
var self = this,
_config = self.config;
$(_config.targetElem).each(function(){
var supportPlaceholder = 'placeholder' in document.createElement('input');
if(!supportPlaceholder) {
var defaultValue = $(this).attr('placeholder');
$(this).focus(function(){
var pattern = new RegExp("^" + defaultValue + "$|^$");
pattern.test($(this).val()) && $(this).val('').css('color',_config.curColor);
}).blur(function(){
if($(this).val() == defaultValue) {
$(this).css('color',_config.defaultColor);
}else if($(this).val().length == 0){
$(this).val(defaultValue).css('color', _config.defaultColor);
}
}).trigger('blur');
}
});
}
};
new Placeholder({});