uniapp 自動獲取焦點


uniapp 自動獲取焦點

在 uniapp 日常開發中常常會遇到需要制動獲取文本框焦點的時候,下面我把大家可以爬的坑都爬完了。

  1. 首先得在 input 元素上設置 foucs 屬性,並且綁定一個變量。
<input class="inputs" type="text" v-model="first" :focus="firstFocus" @change='firstChange'/>
  1. 然后將變量在 data 里面初始化為 false。
firstFocus: false
  1. 然后再 methods 里綁定方法,初始化 focus 屬性后就可以將任意一個的 input 元素獲取焦點了。
// 第一個文本框 change 事件
firstChange() {
	this.secondFocus = false; // 每次都要初始化 focus 屬性
	setTimeout(() => {
		this.secondFocus = true; // this.secondFocus 是第二個文本框的 focus 屬性。
	},0)
}

上四個文本框的完整代碼

<template>
	<view class="content">
			<view class="input-row">
				<view class="titleview"><text class="title">第一個文本框:</text></view>
				<input class="inputs" type="text" v-model="first" :focus="firstFocus" @change='firstChange' />
			</view>
			<view class="input-row">
				<view class="titleview"><text class="title">第二個文本框 :</text></view>
				<input class="inputs" type="text" v-model="second" :focus="secondFocus" @change='secondChange' />
			</view>
			<view class="input-row">
				<view class="titleview"><text class="title">第三個文本框:</text></view>
				<input class="inputs" type="text" v-model="third" :focus="thirdFocus" @change='thirdChange' />
			</view>
			<view class="input-row">
				<view class="titleview"><text class="title">第四個文本框:</text></view>
				<input class="inputs" type="text" v-model="fourth" :focus="fourthFocus" @change='fourthChange' />
			</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				first: '',
				firstFocus: false,
				second: '',
				secondFocus: false,
				third: '',
				thirdFocus: false,
				fourth: '',
				fourthFocus: false
			}
		},
		methods: {
			// 第一個文本框 change 事件
			firstChange() {
				this.initialization();
				setTimeout(() => {
					this.secondFocus = true;
				},0)
			},
			// 第二個文本框 change 事件
			secondChange() {
				this.initialization();
				setTimeout(() => {
					this.thirdFocus = true;
				},0)
			},
			// 第三個文本框 change 事件
			thirdChange() {
				this.initialization();
				setTimeout(() => {
					this.fourthFocus = true;
				},0)
			},
			// 第四個文本框 change 事件
			fourthChange() {
				this.initialization();
				setTimeout(() => {
					this.firstFocus = true;
				},0)
			},
			// 初始化所有焦點變量
			initialization() {
				this.firstFocus = false;
				this.secondFocus = false;
				this.thirdFocus = false;
				this.fourthFocus = false;
			},
		}


	}
</script>

注意的點

  1. 每次想要自動獲取焦點的時候要把所有的 focus 屬性全部初始化為 false。
  2. 同時只允許一個 focus 屬性為 true。
  3. 設置延時函數的作用是因為如果聚焦到下一個文本框后想重新回來修改當前的文本框會導致聚焦失敗。
  4. setTimeout 也可以用 this.nextTick 代替,都是在頁面元素重新渲染之后才會執行內部代碼。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM