Skip to content

Instantly share code, notes, and snippets.

@holyzfy
Created January 22, 2014 09:17
Show Gist options
  • Save holyzfy/8555770 to your computer and use it in GitHub Desktop.
Save holyzfy/8555770 to your computer and use it in GitHub Desktop.
跨浏览器的html5 placeholder属性解决方案
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>placeholder</title>
<style>
.placehoder_wrap {position: relative;}
.placehoder_wrap label {display: none; position: absolute; left: 3px; top: 1px; color: #ccc; font-size: 12px; padding: 3px; line-height: 20px; white-space: nowrap; cursor: text;}
.field {width: 200px; border: 1px solid #000; height: 20px; padding: 3px; font-size: 12px;}
textarea.field {width: 300px; height: 200px;}
</style>
<script src="http://libs.baidu.com/jquery/1.8.0/jquery.min.js"></script>
</head>
<body>
<div class="placehoder_wrap"><label>用户名</label><input type="text" class="field" placeholder="用户名"></div>
<br>
<div class="placehoder_wrap"><label>密码</label><input type="password" class="field" placeholder="密码"></div>
<br>
<div class="placehoder_wrap"><label>内容</label><textarea class="field" cols="30" rows="10" placeholder="内容"></textarea></div>
<script>
$(function(){
var support = 'placeholder' in document.createElement('input');
if(support) return;
function getUid() {
var id = 1;
return id++;
}
var fnMap = {};
setInterval(function(){
for(var i in fnMap){
fnMap[i]();
}
}, 100);
$("input[placeholder], textarea[placeholder]").each(function(){
var id = getUid();
var $field = $(this);
var $label = $(this).siblings("label");
$label.click(function(){
$field.trigger("focus");
});
$field.on({
focus: function(){
fnMap[id] = function(){
$label.toggle($field.val().length < 1);
};
},
blur: function(){
delete fnMap[id];
$label.toggle($field.val().length < 1);
}
});
$field.trigger("blur");
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment