本教程将介绍如何创建扩展搜索输入:当用户单击搜索图标时会展开。

HTML结构

您会注意到这是一个搜索类型的输入,而不是文本。两者之间没有真正的区别,但在我们的例子中搜索在语义上是正确的。
“搜索类型的<input>元素是为用户输入搜索查询而设计的文本字段。这些在功能上与文本输入相同,但用户代理的样式可能不同。” — mdn
使用 CSS 设计样式
我们要做的第一件事是使用 Flexbox 将所有内容居中。将以下样式应用到主体上。
body {
display: flex;
align-items: center;
justify-content: center;
background-color: gray;
min-height: 100vh;
}接着,我们设计完整的搜索输入:
.search-wrapper {
width: 50px;
height: 50px;
display: flex;
border-radius: 4rem;
background: #fff;
align-items: center;
justify-content: center;
outline: none;
border: 2px solid #888;
}我们还向包装 div 元素添加了样式display: flex,以便子元素 ie input 和 button 也将居中。对于输入元素,设置border:none和outline:none。我们还希望它具有完整的宽度和高度。
将 a 设置margin-left:20px为占位符文本和一些填充。
.search-wrapper input {
width: 100%;
height: 100%;
padding: 10px;
margin-left: 20px;
outline: none;
border: none;
font-size: 1.5rem;
}要使图标可见,请为按钮设置背景颜色。使用 将按钮圆化border-radius:50%,并通过设置将其定位到包装元素的右侧margin-left: auto。样式将如下所示:
.search-btn {
font-size: 2rem;
border-radius: 50%;
padding: 10px;
border: 2px solid white;
width: 60px;
cursor: pointer;
height: 60px;
background: #e66610;
margin-left: auto;
}扩展功能
现在整个搜索输入已经完成,我们可以处理扩展功能了。我们要做的第一件事是减少包装元素的宽度。
.search-wrapper {
width: 60px;
height: 60px;
display: flex;
border-radius: 4rem;
background: white;
align-items: center;
justify-content: center;
border-radius: 100px;
outline: none;
}接下来,设置position:relative 为包装 div 元素和position:absolute输入元素;这将确保输入的位置是相对于父元素而不是主体的。
.search-wrapper {
/* the rest of the CSS */
position: relative;
}
.search-wrapper input {
position: absolute;
top: 0;
left: 0;
/* the rest of the CSS */
}现在我们有这样的东西。

正如您所看到的,我们仍然需要额外的 CSS。
z-index:1让我们通过设置按钮 使按钮浮动在输入的顶部。
.search-btn {
font-size: 2rem;
border-radius: 50%;
padding: 10px;
border: 1px solid #be0671;
width: 60px;
cursor: pointer;
height: 60px;
background: #be0671;
margin-left: auto;
z-index: 1;
}最终样式是通过overflow: hidden在包装器 div 元素上进行设置来隐藏任何溢出。
.search-wrapper {
/* rest of the CSS */
overflow: hidden;
}JavaScript 功能
当鼠标悬停在 JavaScript 上时变宽,移开变小。
CSS:
.active {
width: 350px;
}选择包装 div 元素
const search = document.querySelector(".search-wrapper");接下来,添加两个事件***器,mouseover然后mouseout。在 上mouseover,我们将添加活动 CSS 样式;在 上mouseout,我们将删除 CSS 样式。

最终演示效果:
最后一步是添加过渡效果,使过渡效果平滑。
.search-wrapper {
/* the rest of the CSS */
transition: 400ms ease-in-out;
}自行调整过渡值,这就是本教程的内容;查看下面的 CodePen。
See the Pen Expanding Search Box by Envato Tuts+ (@tutsplus) on CodePen.
结论
本教程介绍了如何创建一个扩展搜索栏,其中包含动画以提高交互性。在设计中融入过渡对于使用户界面更具吸引力和愉悦感至关重要。


































发表评论