一、微信小程序輸入框離鍵盤高度
在小程序開發中,經常會遇到輸入框與鍵盤高度的問題,特別是在不同設備上。而微信小程序官方提供了wx.getSystemInfo方法來獲取不同設備的寬高,然後再通過頁面的高度減去輸入框距離底部的距離,即可得到鍵盤彈出時輸入框應該上移的距離。
//獲取系統信息
wx.getSystemInfo({
success: function (res) {
that.setData({
windowWidth: res.windowWidth,
windowHeight: res.windowHeight
});
}
});
//監聽頁面高度變化
wx.onWindowResize(function (res) {
that.setData({
windowHeight: res.windowHeight
});
});
//計算鍵盤高度
var query = wx.createSelectorQuery();
query.select('#input-box').boundingClientRect(function (rect) {
that.setData({
keyboardHeight: that.data.windowHeight - rect.bottom - 10
});
}).exec();
二、微信小程序鍵盤遮擋住輸入框
當鍵盤高度超過輸入框距離底部距離時,輸入框會被鍵盤遮擋住,解決方法是在鍵盤彈出時自動上移頁面,以及在鍵盤收起時自動恢復頁面位置。
//監聽鍵盤彈出
wx.onKeyboardHeightChange(function (res) {
that.setData({
pageHeight: that.data.windowHeight + res.height,
keyboardHeight: res.height,
bottom: res.height
});
});
//監聽鍵盤收起
wx.offKeyboardHeightChange(function (res) {
that.setData({
pageHeight: that.data.windowHeight,
keyboardHeight: 0
});
});
三、微信小程序輸入框鍵盤顯示文字
微信小程序輸入框支持設置placeholder,但是當輸入框獲取焦點並彈出鍵盤時,placeholder會被遮擋住,所以需要在鍵盤彈出時改變placeholder為輸入的內容。
//監聽輸入框輸入
bindInput(e) {
this.setData({
value: e.detail.value,
placeholder: ''
});
}
//監聽鍵盤彈出
onKeyboardHeightChange() {
this.setData({
placeholder: this.data.value
});
}
四、微信小程序輸入框傳值
微信小程序輸入框可以通過value屬性來獲取輸入內容,也可以通過bindInput事件監聽輸入的內容變化。而傳遞輸入框的值可以通過data來進行數據共享。
//在index.js
Page({
data: {
inputValue: ''
},
bindInput(e) {
this.setData({
inputValue: e.detail.value
});
}
});
//在index.wxml
//在其他文件中
var inputVal = getApp().data.inputValue;
五、微信小程序輸入框光標位置
微信小程序輸入框在獲取焦點後會自動彈出鍵盤,此時光標位置也會改變。可以通過設置selectionStart和selectionEnd屬性來手動控制光標的位置。
//在onFocus事件中設置
bindFocus(e) {
this.setData({
selectionStart: e.detail.value.length,
selectionEnd: e.detail.value.length
});
}
//在模板中設置
//在其他事件中獲取光標位置
var selectionStart = e.detail.value.selectionStart;
var selectionEnd = e.detail.value.selectionEnd;
六、微信小程序輸入框顯示不出來
當微信小程序輸入框顯示不出來時,可能是由於頁面布局導致的。可以通過微信小程序提供的調試工具來進行頁面布局的調整,以解決輸入框顯示不出來的問題。
七、微信小程序輸入框換行
微信小程序輸入框可以通過設置textarea屬性來實現多行輸入,而換行則是通過按下回車鍵來實現。
八、微信小程序輸入框獲取數據
微信小程序輸入框獲取數據可以通過value屬性或bindInput事件來實現,也可以通過setData來進行數據共享。
//在index.js
Page({
data: {
inputValue: ''
},
bindInput(e) {
this.setData({
inputValue: e.detail.value
});
}
});
//在其他事件中獲取輸入框的值
var inputVal = e.detail.value;
九、微信小程序輸入框代碼
微信小程序輸入框的代碼如下:
十、微信小程序輸入框彈出數字鍵盤選取
微信小程序輸入框彈出數字鍵盤選取可以通過設置type屬性為number來實現。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/237372.html