文本框特效:获取焦点时自动清除默认文本 失去焦点重新显示默认文字

本文介绍了一种方法,通过HTML和JavaScript实现文本框获取焦点时自动清除默认文本,失去焦点时重新显示默认文字的效果。利用onfocus和onblur事件,结合条件判断,可以优雅地处理输入框的默认文本显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码

<input style="background-image:url(input.gif);background-repeat:no-repeat;padding-left:46px;" type='text' name='keyword' size='23' value='输入关键字' maxlength='50' onfocus="if(this.value='输入关键字')this.value=''" onblur="this.value='输入关键字'"/>

background-image:url(input.gif); 给文本框设置背景图片

onfocus="if(this.value='输入关键字 ')this.value=''" 获取焦点(即鼠标点击文本框)时自动清除文本框文字内容

onblur="this.value='输入关键字'"/ 失去焦点(即鼠标点击文本框以外的区域)时返回显示文本框默认文字内容

只清除文本时还可以用 onClick=this.value=''"

 

----------------------------------------------------------------------------------------------------

输入框失去焦点时 默认值为灰色  代码:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>烈火网 - 关注站长,建设互联网!</title>
<style>
html,body{margin:200px 400px;}
#search{color:#aaa;width:270px;border:1px solid #CC0000;padding:1px; }
</style>
</head>
<body>
<input type="text" value="烈火网(LieHuo.Net)-关注站长,建设互联网!" id="search" />
<script language="javascript">
    var s=document.getElementById("search");
    s.onfocus=function(){if(this.value==this.defaultValue)this.value=''};
    s.onblur=function (){if(/^\s*$/.test(this.value)){this.value=this.defaultValue;this.style.color='#aaa'}}
    s.onkeydown=function(){    this.style.color='#333'}
</script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值