Vue实现带动画的搜索栏:如何设置右侧展开并使用Font Awesome替换背景图标
修改后的完整代码
Template
<template> <span id="demo-2"> <input type="search" placeholder="Search"> <i class="fa fa-search"></i> <!-- 图标类名按引入的Font Awesome版本调整,v5+为fas fa-search --> </span> </template>
Style Scoped
input { outline: none; } input[type=search] { -webkit-appearance: textfield; -webkit-box-sizing: content-box; font-family: inherit; font-size: 100%; } /* 外层容器布局 */ #demo-2 { position: relative; display: inline-flex; justify-content: flex-end; } /* FA图标样式 */ #demo-2 .fa-search { position: absolute; right: 10px; top: 50%; transform: translateY(-50%); pointer-events: none; /* 避免遮挡input点击事件 */ color: #666; } input[type=search] { background: #ededed; /* 移除原背景图配置 */ border: solid 1px #ccc; padding: 9px 10px 9px 32px; width: 55px; -webkit-border-radius: 10em; -moz-border-radius: 10em; border-radius: 10em; -webkit-transition: all .5s; -moz-transition: all .5s; transition: all .5s; } #demo-2 input[type=search] { width: 15px; padding-right: 10px; /* 原padding-left改为padding-right */ color: transparent; cursor: pointer; } #demo-2 input[type=search]:hover { background-color: #fff; } #demo-2 input[type=search]:focus { width: 130px; padding-right: 32px; /* 原padding-left改为padding-right */ color: #000; background-color: #fff; cursor: auto; } #demo-2 input:-moz-placeholder { color: transparent; } #demo-2 input::-webkit-input-placeholder { color: transparent; } /* 可选:聚焦后显示占位符 */ #demo-2 input[type=search]:focus::-webkit-input-placeholder { color: #999; } #demo-2 input[type=search]:focus:-moz-placeholder { color: #999; }
核心调整说明
- 右展开效果实现:给外层容器加
inline-flex+justify-content: flex-end,让input右边缘固定,宽度变化时向左延伸,不再从左侧展开 - 图标替换:移除原背景图的url配置,新增独立的Font Awesome图标元素,通过绝对定位放在input内部右侧,
pointer-events: none保证点击事件穿透到input - 样式适配:将原左侧给图标留空的padding全部改为右侧,避免输入文字被右侧图标遮挡
- 可自定义项:初始/聚焦的宽度、过渡时长、图标位置都可以按需调整数值
注:需提前完成Font Awesome的项目引入配置,可通过npm包或本地静态资源方式集成。
内容的提问来源于stack exchange,提问作者vuenewb
相关产品推荐
相关产品推荐

