返回文章列表

跨浏览器的HTML5 placeholder 实现

HTML 5的input元素引入了placeholder的属性,就是为了实现input提示的,但是在不支持HTML5的浏览器下就要考虑兼容问题,下面的这个实现就很好的解决了兼容问题: [code lang="html"] <html> <head> <met...

2 分钟阅读

HTML 5的input元素引入了placeholder的属性,就是为了实现input提示的,但是在不支持HTML5的浏览器下就要考虑兼容问题,下面的这个实现就很好的解决了兼容问题:

[code lang="html"]
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<style>
.placeholder {
color: #a9a9a9;
}
</style>
</head>
<body>
<div class="row">
<input type="text" placeholder="请输入一些文字" />
</div>
<script>

(function() {
var tmp = document.createElement("input");
window.supports = {
// 检测input是否支持placeholder特性
placeholder: "placeholder" in tmp
}
})();

// 绑定input的placeholder
function bindPlaceholder(input) {
if(!window.supports.placeholder) {
var jqInput = $(input),
placeholder = jqInput.attr("placeholder");

if(placeholder) {
if(input.value == "") {
input.value = placeholder;
$(input).addClass("placeholder");
}
jqInput.focus(function() {
if(this.value == placeholder) {
$(this).removeClass("placeholder");
this.value = "";
}
}).blur(function() {
if(this.value == "") {
$(this).addClass("placeholder");
this.value = placeholder;
}
});
}
}
}
$("input[placeholder]").each(function() {
bindPlaceholder(this);
});
</script>
</body>
</html>
[/code]

原文出处:http://www.ued163.com/?p=1468

另有不使用placeholder的常规做法,比直接通过js操作input value要好:
[code lang="html"]
<html>
<head>

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>

<style>
.row {
position: relative;
padding: 1px;
}
.row .hint{
opacity: 0.4;
filter:alpha(opacity=40);
padding: 2px 0 0 6px;
position: absolute;
}
.row .textbox {
height: 22px;
outline: none;
border: 1px solid Gray;
padding: 4px 3px 2px;
-webkit-border-radius: 2px
-moz-border-radius: 2px;
}
.focus {
padding: 0;
}
.focus .textbox {
border: 2px solid #7B8AAC;
}

</style>
</head>
<body>
<div class="row">
<label class="hint" for="textbox_name">
<span>请输入查询内容?</span>
</label>
<input class="textbox" type="text" id="textbox_name" />
</div>
<script>
$(function() {
$(".textbox").focus(function() {
var self = $(this);
self.closest(".row").addClass("focus");
self.prev().css("display", "none");
}).blur(function() {
var self = $(this);
self.closest(".row").removeClass("focus");
if(self.val() == "") {
self.prev().css("display", "inline");
}
});
});
</script>
</body>
</html>
[/code]
原文出处:http://www.zhoumingzhi.com/2009/12/17/inline-form-labels/

评论交流

暂无评论,欢迎留下你的想法