通常我們?cè)谝贿M(jìn)入頁(yè)面使用mouted方法執(zhí)行
this.$nextTick(() => {
var sea = document.querySelector('.header-search-input')
sea.focus()
})
即可實(shí)現(xiàn)师痕,經(jīng)測(cè)試安卓可以棘钞,但是ios不能聚焦,也彈出不了鍵盤
搜索資料發(fā)現(xiàn)闸昨,ios之所以不能彈出鍵盤是因?yàn)閕os必須通過(guò)觸發(fā)一個(gè)方法才能拉起鍵盤
這里想著怎么在頁(yè)面中觸發(fā)商佑。
要默認(rèn)觸發(fā)必須得保證該元素存在帽驯,查資料發(fā)現(xiàn) display為none的時(shí)候也不會(huì)觸發(fā)
所以頁(yè)面輸入框元素不能用v-show 更不能用v-if
解決方法:
帶有輸入框頁(yè)面為b頁(yè)面哀托。通過(guò)事件跳到b頁(yè)面的a頁(yè)面
把b頁(yè)面的輸入框?qū)懗山M件
在a頁(yè)面就引用此組件移斩,并將組件的樣式設(shè)為
.inp {
position: absolute;
width: 0px;
height: 0px;
top: -100px;
left: -100px;
z-index: -1;
}
即 在a頁(yè)面不展示此組件 但是要在點(diǎn)擊事件觸發(fā)跳轉(zhuǎn)到b頁(yè)面之前,將a組件的光標(biāo)聚焦---focus方法咬腋。
在b頁(yè)面也同時(shí)使用此組件即可 只是在b頁(yè)面要把輸入框樣式改為正常樣式。
(若有c頁(yè)面返回到b頁(yè)面睡互,需要拉起鍵盤根竿。則需要在c頁(yè)面也引用此輸入組件,樣式設(shè)為隱藏就珠,在c的返回事件里 再調(diào)用一遍focus)
注意:this.$nextTick(() => {
}) 最好將focus方法套在這個(gè)方法里 才能起作用
例子:(忽略我難看的樣式)
輸入框組件
<template>
<div :class="{'noinp' : !isShow}">
<input type="text" v-model="name" class="inp" />
</div>
</template>
<script>
export default {
components: {},
props: [ 'isShow' ],
name: "inputTest",
data() {
return {
name: ""
};
},
//方法集合
methods: {
focusFun() {
var inp = document.getElementsByClassName("inp")[0];
inp.focus();
}
}
};
</script>
<style scoped>
section {
width: 100%;
height: 100%;
}
.inp {
display: block;
box-sizing: border-box;
margin: 100px auto;
width: 80%;
height: 44px;
font-size: 20px;
border: none;
padding: 10px;
line-height: 24px;
outline: none;
background-color: #f0f0f0;
}
.noinp {
position: absolute;
top: -100px;
width: 0px;
height: 0px;
left: -100px;
z-index: -1;
overflow: hidden;
}
</style>
a頁(yè)面
<template>
<section>
<input-test ref="inp" :is-show="isShow"></input-test>
<div class="btn" @click="goNext">去輸入頁(yè)</div>
</section>
</template>
<script>
import inputTest from '../base/input-test'
export default {
data() {
return {
isShow: false
};
},
components: {
inputTest
},
//方法集合
methods: {
goNext() {
console.log('------------');
this.$refs.inp.focusFun();
this.$router.push('./testKeyb')
}
}
};
</script>
<style scoped>
.btn{
width: 100px;
height: 30px;
background-color: violet;
}
</style>
b頁(yè)面
<template>
<section>
<input-test ref="inp" :is-show="isShow"></input-test>
</section>
</template>
<script>
import inputTest from '../base/input-test'
export default {
data() {
return {
isShow: true
};
},
components: {
'input-test': inputTest
},
//生命周期 - 掛載完成(可以訪問(wèn)DOM元素)
mounted() {
this.$refs.inp.focusFun();
},
//方法集合
methods: {
}
};
</script>
<style scoped>
</style>