如何在css中点击搜索图标时展开小方块输入框?

fla*_*ash 16 html javascript css font-awesome

我有一个搜索栏,最左边搜索图标,如下面小提琴 和下面的屏幕截图所示.

在此输入图像描述

我用来制作搜索图标和方形边框的HTML和CSS代码是:


HTML:

<form class="back">
  <span class="fa fa-search searchicon" aria-hidden="true"> 
</span>
  <input type="text" name="search" class="extand ">
</form>
Run Code Online (Sandbox Code Playgroud)


CSS:

.back{
  padding: 0.5%;
  background: #10314c;

}

.searchicon {
   float: left;
   margin-top: -20px;
   position: relative;
   top: 26px;
   left: 8px;
   color: white;
   z-index: 2;
   }

.extand {
    width: 2.4%;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
    background: #10314c;
    background-position: 10px 10px;
    background-repeat: no-repeat;
    -webkit-transition: width 0.4s ease-in-out;
    transition: width 0.4s ease-in-out;
}
.extand-now {
    width: 50%;
}
Run Code Online (Sandbox Code Playgroud)


问题陈述:

如果我点击搜索图标,搜索图标周围的小方块输入框(在屏幕截图中用箭头标记)应该与此处类似.

这是我更新的小提琴,它几乎正常工作,但这两件事我无法弄清楚如何做到这一点:

  • 击中外面的任何地方后,方框应该回到原来的位置.
  • 当白色方形边框扩展时,内部背景应为白色.

有关如何做到这一点的任何想法?

Gau*_*aik 10

这是更新的小提琴链接

.searchicon {
   float: left;
   margin-top: -20px;
   position: relative;
   pointer-events:none; /*Add this to ur css*/
   top: 26px;
   left: 8px;
   color: white;
   z-index: 2;
   }

.extand {
    width: 2.4%;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
    background: #10314c;
    background-position: 10px 10px;
    background-repeat: no-repeat;
    -webkit-transition: width 0.4s ease-in-out;
    transition: width 0.4s ease-in-out;
}
.extand:focus {
  width: 50%;
  background: white;
}
.extand:focus + span{  /*hide icon*/
  display:none;
}
Run Code Online (Sandbox Code Playgroud)

无需添加javascript.在点击输入时,它会被聚焦,可以在css中使用它来定位它并为其添加宽度,当你点击外面时,输入变得没有聚焦并返回到原始大小


小智 6

我认为你不会使用javascript,你应该依赖于焦点,可以在css中使用它来定位它并为它添加宽度,当你点击外面时,输入变得没有焦点并返回到原始大小

input{
    width: 130px;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
    background-color: white;
    background-image: url(https://i.imgur.com/MACjo6S.png);
    background-position: 10px 10px; 
    background-repeat: no-repeat;
    padding: 12px 20px 12px 40px;
    -webkit-transition: width 0.4s ease-in-out;
    transition: width 0.4s ease-in-out;
}

input:focus {
    width: 100%;
}
Run Code Online (Sandbox Code Playgroud)
<form>
  <input type="text" name="search" placeholder="Search..">
</form>
Run Code Online (Sandbox Code Playgroud)


Ign*_*Ara 1

您正在寻找的行为是在您聚焦时修改其宽度(在其中单击鼠标):

input[type=text]:focus {
    width: 100%;
}
Run Code Online (Sandbox Code Playgroud)

但在更改其宽度之前,您需要给它一个较低的值,例如:

input[type=text] {
    width: 20%;
    background: #10314c;
}
Run Code Online (Sandbox Code Playgroud)