在Uniapp开发iOS端应用时,输入框默认出现的放大镜图标是iOS系统原生搜索类输入框的默认样式,当我们在Uniapp中使用input组件且设置type为search时,iOS端会自动添加这个图标,很多时候我们需要去除它来实现自定义的界面效果。

方案一:通过CSS样式覆盖去除图标
iOS端的输入框放大镜图标属于系统原生伪元素样式,我们可以通过CSS的伪元素选择器来隐藏它,这种方式适用性比较广,不需要修改组件的核心属性。
首先给需要处理的input组件添加一个自定义类名,比如no_search_icon,然后在样式中添加如下代码:
/* 去除iOS输入框默认的放大镜图标 */
.no_search_icon::-webkit-search-cancel-button,
.no_search_icon::-webkit-search-decoration,
.no_search_icon::-webkit-search-results-button,
.no_search_icon::-webkit-search-results-decoration {
display: none;
}
/* 兼容iOS系统原生input的搜索图标 */
.no_search_icon input {
-webkit-appearance: none;
}
在Uniapp的vue文件中使用方式如下:
<template>
<view class="content">
<input
class="no_search_icon"
type="search"
placeholder="请输入搜索内容"
v-model="searchValue"
/>
</view>
</template>
<script>
export default {
data() {
return {
searchValue: ''
}
}
}
</script>
<style scoped>
/* 去除iOS输入框默认的放大镜图标 */
.no_search_icon::-webkit-search-cancel-button,
.no_search_icon::-webkit-search-decoration,
.no_search_icon::-webkit-search-results-button,
.no_search_icon::-webkit-search-results-decoration {
display: none;
}
.no_search_icon input {
-webkit-appearance: none;
}
</style>
方案二:修改input组件的type属性
如果我们的输入框不需要搜索类型的专属特性,只是普通的文本输入,可以将input的type从search改为text,这样iOS系统就不会自动添加放大镜图标了。
修改后的代码示例:
<template>
<view class="content">
<input
type="text"
placeholder="请输入搜索内容"
v-model="searchValue"
/>
</view>
</template>
<script>
export default {
data() {
return {
searchValue: ''
}
}
}
</script>
不过这种方式需要注意,type改为text之后,输入框的键盘类型会变成普通文本键盘,不会再默认弹出搜索相关的键盘布局,需要根据实际需求选择。
方案三:使用自定义输入框组件替代原生input
如果以上两种方式都无法满足需求,我们可以自己封装一个自定义的输入框组件,不使用原生的input搜索类型,完全自主控制样式和图标显示。
自定义组件的核心代码示例:
<template>
<view class="custom_input_wrap">
<input
type="text"
placeholder="请输入内容"
v-model="inputValue"
@confirm="handleConfirm"
/>
</view>
</template>
<script>
export default {
props: {
value: {
type: String,
default: ''
}
},
data() {
return {
inputValue: this.value
}
},
watch: {
inputValue(newVal) {
this.$emit('input', newVal)
},
value(newVal) {
this.inputValue = newVal
}
},
methods: {
handleConfirm() {
this.$emit('confirm', this.inputValue)
}
}
}
</script>
<style scoped>
.custom_input_wrap {
padding: 10px;
border: 1px solid #eee;
border-radius: 4px;
}
.custom_input_wrap input {
width: 100%;
height: 36px;
border: none;
outline: none;
-webkit-appearance: none;
}
</style>
注意事项
- CSS样式覆盖的方案需要注意样式的作用域,如果是scoped样式,可能需要使用/deep/或者::v-deep来穿透作用域,确保样式生效。
- 修改type属性的方案会影响键盘的弹出类型,需要确认业务是否允许普通文本键盘。
- 自定义组件方案开发成本稍高,但灵活性最强,适合对输入框样式有高度自定义需求的场景。
以上三种方案都可以有效去除Uniapp iOS端输入框的放大镜图标,开发者可以根据项目的实际需求选择合适的方案。