需求:搜索框占位提示效果
- 获取焦点:如果文字是“请输入关键字”,清空内容,字体改为黑色
- 失去焦点:如果输入框为空,填充提示文字,字体灰色
- 使用class样式控制文字颜色
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm28.aspx.cs" Inherits="WebApplication1.WebForm28" %>
<html xmlns="[http://www.w3.org/1999/xhtml](http://www.w3.org/1999/xhtml)">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="[http://libs.baidu.com/jquery/1.8.3/jquery.min.js](http://libs.baidu.com/jquery/1.8.3/jquery.min.js)"></script>
<script type="text/javascript">
$(function () {
$("#key").focus(function () {
if ($(this).val() == "请输入关键字")
{
$(this).attr("class", "keyblack");
$(this).val("");
}
});
$("#key").blur(function () {
if ($(this).val() == "") {
$(this).attr("class", "keygray");
$(this).val("请输入关键字");
}
});
});
</script>
<style>
.keygray {
color:gray;
}
.keyblack {
color:black;
}
</style>
</head>
<body>
<input type="text" value="请输入关键字" id="key" class="keygray" />
</body>
</html>
Code language: HTML, XML (xml)
说明:
focus():输入框获得光标事件blur():输入框失去光标事件注意:这是JS模拟的占位提示,现代HTML可以直接用placeholder属性实现,但本案例练习jQuery焦点事件。
Previous: 练习一下-完成倒计时功能
Next: 输入框为空红色提示功能