方法一:(缺点:输入时文字和提示文字颜色只能一样)
<input type="text" onblur="if (this.value == '') { this.value = '请输入工号'; }" onfocus="if (this.value == '请输入工号') { this.value = ''; }" value="请输入工号">
方法二:(常用)
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="form-group">
<label>原转诊单号</label>
<input type="text" class="form-control" value="" placeholder="请输入10位转诊单号">
</div>
<script src="js/jquery-1.10.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.placeholder.min.js"></script>
<script>
//placeholder
$(function(){
$(".form-control").placeholder();
});
</script>
</body>
</html>
方法三:
<script type="text/javascript">
if( !('placeholder' in document.createElement('input')) ){
$('input[placeholder],textarea[placeholder]').each(function(){
var that = $(this),
text= that.attr('placeholder');
if(that.val()===""){
that.val(text).addClass('placeholder');
}
that.focus(function(){
if(that.val()===text){
that.val("").removeClass('placeholder');
}
})
.blur(function(){
if(that.val()===""){
that.val(text).addClass('placeholder');
}
})
.closest('form').submit(function(){
if(that.val() === text){
that.val('');
}
});
});
}
</script>
$(function() {
// 如果不支持placeholder,用jQuery来完成
if(!isSupportPlaceholder()) {
// 遍历所有input对象, 除了密码框
$('input').not("input[type='password']").each(
function() {
var self = $(this);
var val = self.attr("placeholder");
input(self, val);
}
);
/**
* 对password框的特殊处理
* 1.创建一个text框
* 2.获取焦点和失去焦点的时候切换
*/
$('input[type="password"]').each(
function() {
var pwdField = $(this);
var pwdVal = pwdField.attr('placeholder');
var pwdId = pwdField.attr('id');
// 重命名该input的id为原id后跟1
pwdField.after('<input id="' + pwdId +'1" type="text" value='+pwdVal+' autocomplete="off" />');
var pwdPlaceholder = $('#' + pwdId + '1');
pwdPlaceholder.show();
pwdField.hide();
pwdPlaceholder.focus(function(){
pwdPlaceholder.hide();
pwdField.show();
pwdField.focus();
});
pwdField.blur(function(){
if(pwdField.val() == '') {
pwdPlaceholder.show();
pwdField.hide();
}
});
}
);
}
});
// 判断浏览器是否支持placeholder属性
function isSupportPlaceholder() {
var input = document.createElement('input');
return 'placeholder' in input;
}
// jQuery替换placeholder的处理
function input(obj, val) {
var $input = obj;
var val = val;
$input.attr({value:val});
$input.focus(function() {
if ($input.val() == val) {
$(this).attr({value:""});
}
}).blur(function() {
if ($input.val() == "") {
$(this).attr({value:val});
}
});
}