CSS 如何在点击搜索图标时扩展小方形输入框
在本文中,我们将介绍如何使用CSS在点击搜索图标时扩展小方形输入框的方法。
阅读更多:https://sotoolbox.com/tag/css target="_blank" rel="nofollow">CSS 教程
问题分析
在一些网页设计中,我们经常会见到一个小方形的输入框,当用户点击搜索图标时,输入框会扩展为一个更宽更长的矩形。这种效果给用户带来更好的交互体验,同时也能更好地适应不同的设备尺寸。
解决方案
下面我们将介绍一种使用CSS实现这种效果的方法。
Step 1 – HTML结构
首先,我们需要在HTML中创建一个输入框和一个搜索图标的容器。代码如下:
<div class="search-box">
<input type="text" placeholder="搜索...">
<div class="search-icon">
<i class="fa fa-search"></i>
</div>
</div>
这里使用了FontAwesome图标库的搜索图标,需要在HTML文件中引入FontAwesome的CSS文件。
Step 2 – CSS样式
接下来,我们需要为输入框和搜索图标添加样式。代码如下:
.search-box {
position: relative;
display: inline-block;
width: 100px; /* 输入框的初始宽度 */
overflow: hidden;
}
input[type="text"] {
width: 100%;
height: 30px;
padding: 5px;
border: none;
border-radius: 5px;
background-color: #f1f1f1;
transition: width 0.3s ease;
}
.search-icon {
position: absolute;
top: 0;
right: 0;
width: 30px;
height: 30px;
background-color: #ccc;
transition: width 0.3s ease;
cursor: pointer;
}
.search-icon i {
color: #fff;
font-size: 16px;
line-height: 30px;
text-align: center;
transition: transform 0.3s ease;
}
.search-box:hover input[type="text"] {
width: 200px; /* 鼠标悬停时输入框的宽度 */
}
.search-box:hover .search-icon {
width: 0; /* 鼠标悬停时搜索图标的宽度 */
}
.search-box:hover .search-icon i {
transform: rotate(360deg); /* 鼠标悬停时搜索图标旋转效果 */
}
Step 3 – 解析实现
上述代码中,我们通过设置输入框的宽度和搜索图标的宽度,并在鼠标悬停时改变它们的宽度,从而实现了输入框的扩展效果。同时,我们还为搜索图标添加了旋转效果,增加了交互性。
示例
下面是一个完整的示例,你可以将代码复制到HTML文件中进行测试:
<!DOCTYPE https://sotoolbox.com/tag/css target="_blank" rel="nofollow">html>
<https://sotoolbox.com/tag/css target="_blank" rel="nofollow">html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/https://sotoolbox.com/tag/css target="_blank" rel="nofollow">ajax/libs/font-awesome/4.7.0/https://sotoolbox.com/tag/css target="_blank" rel="nofollow">css/font-awesome.min.https://sotoolbox.com/tag/css target="_blank" rel="nofollow">css">
<style>
.search-box {
position: relative;
display: inline-block;
width: 100px; /* 输入框的初始宽度 */
overflow: hidden;
}
input[type="text"] {
width: 100%;
height: 30px;
padding: 5px;
border: none;
border-radius: 5px;
background-color: #f1f1f1;
transition: width 0.3s ease;
}
.search-icon {
position: absolute;
top: 0;
right: 0;
width: 30px;
height: 30px;
background-color: #ccc;
transition: width 0.3s ease;
cursor: pointer;
}
.search-icon i {
color: #fff;
font-size: 16px;
line-height: 30px;
text-align: center;
transition: transform 0.3s ease;
}
.search-box:hover input[type="text"] {
width: 200px; /* 鼠标悬停时输入框的宽度 */
}
.search-box:hover .search-icon {
width: 0; /* 鼠标悬停时搜索图标的宽度 */
}
.search-box:hover .search-icon i {
transform: rotate(360deg); /* 鼠标悬停时搜索图标旋转效果 */
}
</style>
</head>
<body>
<div class="search-box">
<input type="text" placeholder="搜索...">
<div class="search-icon">
<i class="fa fa-search"></i>
</div>
</div>
</body>
</html>
只需将上述代码复制到HTML文件中,你就可以看到一个小方形输入框和一个搜索图标。当你将鼠标悬停在输入框上时,输入框会扩展为一个更宽的矩形,搜索图标会消失并带有旋转效果。
总结
通过使用CSS,我们可以很方便地实现在点击搜索图标时扩展小方形输入框的效果。这不仅提供了更好的交互体验,还让网页在不同设备上都能够得到良好的展示效果。希望本文对你有所帮助!
此处评论已关闭