欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

使用JavaScrip模拟实现仿京东搜索框功能

时间:2021-04-03 07:47:26|栏目:JavaScript代码|点击:

使用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用于修饰元素的轮廓;

总结

上一篇:js弹窗返回值详解(window.open方式)

栏    目:JavaScript代码

下一篇:点击文字链接弹出确认框基于js Confirm实现

本文标题:使用JavaScrip模拟实现仿京东搜索框功能

本文地址:http://www.codeinn.net/misctech/93728.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有