JavaScript实现搜索框点击文字消失与失焦恢复

作者:像素漫游时间:2026-10-28 14:14:30浏览:87

本文介绍如何使用JavaScript实现搜索框的交互效果:当输入框获得焦点时,默认文字消失并改变颜色;当失去焦点且内容为空时,默认文字重新出现。通过onfocus和onblur事件结合变量状态判断,实现简洁的表单提示功能。

JavaScript实现搜索框点击文字消失与失焦恢复

实现搜索框的交互效果:当输入框获得焦点时,默认文字消失并改变颜色;当失去焦点且内容为空时,默认文字重新出现。通过onfocus和onblur事件结合变量状态判断,实现简洁的表单提示功能。


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>

<body>
<input id="text" type="text" value="点我就消失"/>
<script>
var oText=document.getElementById("text");
var onoff=true;
oText.color="#000";
oText.onfocus=function(){
if(onoff){
this.value="";
this.color="red";
onoff=false;
}
}

oText.onblur=function(){
if(this.value==''){
this.color="#000";
this.value="点我就消失";
onoff=true;
}
}
</script>
</body>
</html>

作者最新文章