javascript 模仿 html5 placeholder

时间:2024-09-20 18:37:08
 <form action="?action=deliver" method="post" class="deliver-form">
<div class="article-type">
<span>类型:</span>
<?php foreach (range(1,14) as $num){ ?>
<input type="radio" name="type"><img src="data:images/icon<?php echo $num ?>.gif" >
<?php } ?>
</div>
<div class="article-tit">
<input type="text" id="title" name="article-title" value="请输入标题">
</div>
<div class="article-cont">
<textarea name="article-text" id="textarea" cols="30" rows="10">请输入帖子内容</textarea>
</div>
<div class="code-sub">
<input type="text" name="code" value="请输入4位验证码" id="code-ipt"><img src="code.php" alt="验证码" id="code">
<input type="submit" value="发表" class="sub">
</div>
</form>

js

//input模仿placeholder,参数id是input的id,value为input的value
//如果为textarea的话,value则为textterea的默认内容(textarea不能在value使用默认值)
//value首先要在html中定义
//默认文字的颜色可以先在css中声明
function _placeholder(id,value){
var _text = document.getElementById(id);
_text.onblur = function(){
if(this.value == ''){
this.style.color='#666';
this.value = value;
}
}
_text.onfocus = function(){
if(this.value == value){
this.value = '';
this.style.color='#333';
}
}
}
_placeholder('title','请输入标题');
_placeholder('textarea','请输入帖子内容');
_placeholder('code-ipt','请输入4位验证码');