JavaScrip实现仿京东搜索框

使用js模拟实现京东的搜索框,主要用了js中的onfocus(注册焦点事件),onblur(失去焦点的事件);

主要实现了:

  1. 在鼠标点进去的时候,里面的默认内容消失;
  2. 在输入之后,再点击搜索框外,输入的内容还在搜索框中;
  3. 如果输入为空,点击搜索框外,里面自动显示默认内容;
  4. 内容颜色的改变

 
 
效果图

代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>京东搜索框</title>
		<style type="text/css">
			*{
				margin: 0;
				padding: 0;
				border: 0;
			}
			#search{
				width: 550px;
				height: 35px;
				margin: 100px auto;
			}
			#search input{
				width: 492px;
				height: 31px;
				border: 2px solid #f10215;
				outline-style: none;/* 消除原来的边框默认属性 */
				float: left;
				padding-left: 4px;/* 让文字在搜索的时候距离框4px */
				color: #888;
			}
			#search button{
				width: 50px;
				height: 35px;
				background-color: #f10215;
				float: left;
				color: white;
			}
		</style>
		<script type="text/javascript">
			var keyword = "iphone 11";//搜索框中默认的搜索词
			window.onload = function(){
				//得到按钮的对象
				var btnsearch = document.getElementById("search").getElementsByTagName("button")[0];
				//得到搜索框的对象
				var txt = document.getElementById("search").getElementsByTagName("input")[0];
				//为搜索框注册焦点事件
				txt.onfocus = function(){
					//当在焦点上时让搜索框文字变成黑色
					txt.style.color = "black";
					//如果搜索框为关键字的时候,注册焦点就让搜索框为空
					if (txt.value == keyword) {
						txt.value = "";
					}
				}
				//为搜索框注册失去焦点事件
				txt.onblur = function(){
					//在失去焦点的时候如果搜索框内容为空,就让搜索框显示默认关键字
					if (txt.value == "") {
						this.value = keyword;
						this.style.color = "#888";
					}
				}
			}
		</script>
	</head>
	<body>
		<div id="search">
			<input type="text" value="iphone 11" />
			<button>搜索</button>
		</div>
	</body>
</html>

  • onfocus事件:事件在对象获得焦点时发生,常用在表单中
  • onblur事件:事件在对象失去焦点时发生

css中的属性:outline用于修饰元素的轮廓;

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值