键盘
自动弹出
执行input的focus方法,安卓是适配的,但是iOS Safari只允许在用户真实交互事件(如touchstart、click等)的事件处理函数中触发键盘
注意事项
- 事件监听器必须是
click或touchend,不能是mouseover等非用户意图的事件。 - readonly处理 :移除readonly属性确保input可以获得焦点
- 不要使用
display: none或visibility: hidden来隐藏输入框,这会导致 iOS 无法聚焦。 - 在异步代码中包装 focus()(会失败)
// 这行不通!
setTimeout(() => {
hiddenInput.focus(); // 在 iOS 上无效
}, 1000);
// 这也不行!
fetch('some-api.com').then(() => {
hiddenInput.focus(); // 在 iOS 上无效
});
案例:实现点击按钮,弹出弹框并实现键盘自动弹出
遇到问题:分别由上面的3,4解决。4不只是输入框,当弹框是display也不行
<van-field
class="form-eqa-select nsrmcField"
v-model="form.nsrmc"
label="单位名称"
placeholder="请输入"
readonly
required
ref="nsrmcField"
>
mounted() {
const fieldButton = this.$refs.nsrmcField.$el;
fieldButton.addEventListener("click", () => {
console.log("fieldButton", fieldButton);
this.$refs.searchPickerRef.showPicker = true;
});
}
下面我是封装的组件
<template>
<van-popup
v-model="showPicker"
position="bottom"
style="height: 80%"
:get-container="getContainer"
:close-on-click-overlay="true"
round
:lazy-render="false"
ref="popupRef"
>
<van-search
ref="searchInput"
shape="round"
v-model="searchValue"
:placeholder="searchPlaceholder"
@input="onSearch"
/>
</van-popup>
</template>
<script>
export default {
watch: {
showPicker: {
handler(newVal) {
if (!newVal) {
this.reset();
this.updateList([]);
} else {
this.$refs.popupRef.$el.style.visibility = "visible";
this.$refs.popupRef.$el.style.display = "block";
}
console.log("this.$refs.popupRef.$el", this.$refs.searchInput.getElementsByTagName("input"));
if (this.$refs.searchInput) {
const hiddenInput = this.$refs.searchInput.getElementsByTagName("input")[0];
console.log("hiddenInput2", hiddenInput);
if (hiddenInput) {
hiddenInput.focus();
hiddenInput.click();
}
}
}
}
},
mounted() {
if (this.$refs.fieldRef) {
const fieldButton = this.$refs.fieldRef.$el;
fieldButton.addEventListener("click", () => {
console.log("fieldButton", fieldButton);
this.showPicker = true;
});
}
}
};
</script>