JavaScript实现输入框获取与失去焦点时的样式切换
作者:白露时间:2026-10-28 21:13:51浏览:322
本文介绍如何使用JavaScript控制输入框在获取和失去焦点时的状态显示。通过定义不同的CSS类,并在input标签中绑定onFocus和onBlur事件,实现输入框边框颜色的动态切换,提升用户交互体验。
JavaScript实现输入框焦点状态切换
本文详细介绍了一种利用JavaScript实现输入框在获取焦点和失去焦点时动态切换显示状态的方法。该方案旨在帮助开发者优化用户界面交互,具体实现逻辑如下所示。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>边框变色</title>
<style type="text/css">
<!--
.SearchKeyword {border:1px solid #797A75;width: 202px;color: #CDCDCD;font-size:12px;}
.SearchKeywordonFocus {border:1px solid #ABCD3A;width: 202px;color: #000000;font-size:12px;}
-->
</style>
<script language="javascript">
function keywordfocus()
{
if (document.formSearch.keyword.value == '请输入关键字')
{
document.formSearch.keyword.value = '';
document.formSearch.keyword.className = 'SearchKeywordonFocus';
}
}
function keywordblur()
{
if (document.formSearch.keyword.value == '')
{
document.formSearch.keyword.value = '请输入关键字';
document.formSearch.keyword.className = 'SearchKeyword';
}
}
</SCRIPT>
</head>
<body>
<form id="formSearch" name="formSearch" method="post" action="">
<input type="text" name="keyword" class="SearchKeyword" value="请输入关键字" onFocus="keywordfocus();" onBlur="keywordblur();" />
</form>
</body>
</html>
希望上述关于JavaScript程序设计的示例内容能对读者的实际开发工作提供有益的参考与帮助。
作者最新文章
AOS.js 动画不触发怎么办?排查 DOM 加载与移动端兼容问题
2026-11-05 17:02:26
sigma.js 怎么实现节点点击、拖拽与悬停提示交互
2026-11-05 15:03:27
Matter.js 与 PixiJS/Three.js 集成:分离物理计算与渲染
2026-11-05 13:43:48
主流JS弹幕库选型指南:Danmaku.js等库的功能与体积对比
2026-11-05 09:28:19
JavaScript点击事件监听与交互效果实例
2026-11-05 09:10:19
