马上就到双十一了,我们在京东淘宝购物,疯狂剁手的同时,有没有注意到京东的搜索框呢,除了能进行搜索内容以外,它的样式又是如何实现的呢?
下面就分析一下如何实现仿京东的搜索框。
核心分析:
JavaScript部分:
1、当文本框获取焦点的时候,div中的字体颜色变为rgb(200,200,200);
2、当文本框失去焦点事件发生时,div中的字体颜色变成原来的样式#989898;
3、当文本框输入内容时,div的属性变为 none,表现效果为文字消失;
4、当清除文本框里面内容时,divdiv的属性变为 inline-block,表现效果为文字消失;
因为是在文本框里面显示出来的内容,改变的是表单元素,判断文本框里面是否有输入内容,判断的依据是 表单的value值是否为 空字符串。
实现代码:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- ? ? <meta charset="UTF-8">
- ? ? <title>仿京东搜索框</title>
- ? ? <style>
- ? ? *{
- ? ? ? ? margin: 0;padding:0;
- ? ? }
- ? ? .from{
- ? ? ? ? border:2px solid #e2231a;
- ? ? ? ? width:490px;
- ? ? ? ? height:36px;
- ? ? ? ? position:relative;
- ? ? ? ? margin:100px auto;
- ? ? ? ? font-size: 12px;
-
- ? ? }
- ? ? .text{
- ? ? ? ? position:absolute;
- ? ? ? ? line-height: 36px;
- ? ? ? ? left:27px;
- ? ? ? ? color:#989898;
- ? ? ? ? z-index:-1;
- ? ? }
- ? ? .search{
- ? ? ? ? position:absolute;
- ? ? ? ? left:22px;
- ? ? ? ? width:430px;
- ? ? ? ? height:34px;
- ? ? ? ? outline:none;
- ? ? ? ? border:1px solid transparent;
- ? ? ? ? background:transparent;
- ? ? ? ? line-height: 34px;
- ? ? ? ? overflow: hidden;
-
- ? ? }
- ? ? .button{
- ? ? ? ? position:absolute;
- ? ? ? ? right:0px;
- ? ? ? ? width:58px;
- ? ? ? ? height:36px;
- ? ? ? ? background-color: #e2231a;
- ? ? ? ? border:1px solid transparent;
- ? ? ? ? margin:auto;
- ? ? ? ? outline:none;
- ? ? ? ? cursor: pointer;
- ? ? }
- ? ? button:hover{
- ? ? ? ? background-color: #c81623;
- ? ? }
- ? ? span img{
- ? ? ? ? position:absolute;
- ? ? ? ? right:65px;
- ? ? }
-
- ? ? </style>
- </head>
- ? ? <div class='from'>
- ? ? ? ? <div class='text'>暗夜游戏本</div>
- ? ? ? ? <input type="text" class="search" value=''>
- ? ? ? ? <span class='photo' title="未选择取任何文件">
- ? ? ? ? ? ? <img src="camera.png" alt="">
- ? ? ? ? </span>
- ? ? ? ? <button class='button'>
- ? ? ? ? ? ? <i><img src="search.png" ?alt=""></i>
- ? ? ? ? </button>
- ? ? </div>
- <body>
- ? ? <script>
- ? ? var div = document.querySelector('.from');
- ? ? var input = document.querySelector('.search');
- ? ? var text = document.querySelector('.text');
- ? ? input.onfocus = function(){
- ? ? ? ? text.style.color = 'rgb(200,200,200)'
- ? ? }
- ? ? input.onblur = function(){
- ? ? ? ? text.style.color = '#989898'
- ? ? }
- ? ? input.oninput = function(){
- ? ? ? ? text.style.display = 'none';
- ? ? if (input.value == '') {
- ? ? ? ? text.style.display = 'inline-block';
- ? ? }; ? ?}
- ? ? </script>
- </body>
- </html>
显示效果:
1、未触发事件的状态

2、输入框里获取焦点的状态

3、输入框里输入内容

4、删除里面内容后

5、CSS样式效果(hover)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。