您的位置:首页 > 编程语言 > Java开发

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

2019-10-16 18:07 806 查看

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

总结

以上所述是小编给大家介绍的使用JavaScrip模拟实现仿京东搜索框功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  js 京东 搜索框