效果:当第一次点击input文本框时,原本默认的文本隐藏,然后可自由输入文本,如果有输入的文本,鼠标经过input文本框时,默认全选文本内容,以便删除;点击文本框可取消全选。
关键知识:
onfocus事件、onblur事件、onmouseover事件、select()方法
具体代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>点击隐藏文字</title>
<style>
.search {
width:258px;
height: 40px;
background-color: pink;
margin:100px auto;
}
.search input,.search button{
border: 0 none;
padding: 0;
}
.search input {
width:206px;
height: 40px;
background: url(images/left.jpg) no-repeat;
padding-left: 10px;
float: left;
color:#ccc;
outline-style: none;/*清除获得焦点时蓝色边框*/
}
.search button {
width:42px;
height: 40px;
background: url(images/right.jpg) no-repeat;
float: left;
}
</style>
</head>
<body>
<div class="search">
<input type="text" value="请输入..." id="txt">
<button></button>
</div>
</body>
<script type="text/javascript">
var txt = document.getElementById('txt');
txt.onfocus = function(){//得到焦点
if(txt.value == '请输入...'){
//用户第一次使用搜索框
txt.value = '';
txt.style.color = '#333';//字体颜色
}
}
txt.onblur = function(){//失去焦点
if(txt.value == ''){
//用户未输入
txt.value = '请输入...';
txt.style.color = '#ccc';
}
}
txt.onmouseover = function(){//鼠标经过表单全选
this.select();
}
</script>
</html>
具体效果可见:点击隐藏文字+鼠标经过表单