原先的样子
点击之后
如果没有输入内容则还原
否则为最新输入
实现代码
test.html
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<div class="box">
<span>单击文本框清空原有内容,离开文本框时若未填写内容则设置为之前的内容:</span>
<div class="content">
<input type="text" name="name" value="Lucas"/>
</div>
</div>
<style>
div.box{width:300px;padding:20px;margin:20px;border:4px dashed #ccc;}
div.box span{color:#999;font-style:italic;}
div.content{width:250px;margin:10px 0;padding:20px;border:2px solid #ff6666;}
input[type='text']{width:200px;height:35px;padding:5px 10px;margin:5px 0;border:1px solid #ff9966;}
</style>
<script>
$(function(){
var text; // 全局变量用于保存文本框的内容
$("input:text").focus(function() {
text = $(this).val();
$(this).val("");
});
$("input:text").blur(function() {
$(this).val()!="" || $(this).val(text);
});
})
</script>