思路是将label定位到输入框上面,根据输入框内容判断显示或者隐藏label,当然如果浏览器支持html5则就使用placeholder功能就ok了,所以可以预先判断一下是否支持。方法很简单,下面代码直接运行可以实现效果。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<script type="text/javascript" src="jquery-1.8.2.js"></script>
<style type="text/css">
ul,li{list-style:none;margin:5px 0px;padding:0px;}
.label-text-tips{margin-bottom:-30px;float:left;color:black;height:25px;line-height:20px;color:#ccc;}
.txt-mobile{position:relative;z-index:22;background-color:transparent;border:solid 1px #ccc;}
</style>
<script type="text/javascript">
<!--
$(document).ready(function(){
if (!IsPlaceholderSupport())
{
CopyPlaceholder("la","txt_mobile");
CopyPlaceholder("la2","txt_mobile2");
}
})
function IsPlaceholderSupport() {
return 'placeholder' in document.createElement('input');
}
function CopyPlaceholder(labelId,txtId)
{
$("#"+txtId).before("<label class=\"label-text-tips\" id=\""+labelId+"\">请输入</label>");
if ($("#"+txtId).val()=="")
{
$("#"+labelId).show();
}
else
{
$("#"+labelId).hide();
}
$("#"+txtId).keyup(function(){
if($(this).val()=="")
{
$("#"+labelId).show();
}
else
{
$("#"+labelId).hide();
}
})
}
//-->
</script>
</head>
<body>
<div>
<ul>
<li>
<input id="txt_mobile" type="text" value="12" placeholder="请输入" />
</li>
<li>
<textarea id="txt_mobile2" placeholder="请输入"></textarea>
</li>
</ul>
</div>
</body>
</html>