微信小程式開發-textarea高度問題
阿新 • • 發佈:2019-01-27
正在做一個記事本的小程式
記事自然少不了textarea元件
編輯頁面我的設計是上面一行標題欄,下面一行按鈕操作區,中間就是textarea填充剩餘空間
效果如下圖
使用flex佈局很容易就做到上述效果,一個container包含一個豎直排列的三個view
中間的view放textarea
<!--index.wxml--> <form bindsubmit="onSubmit" bindreset=""> <view class="container"> <view class='title'> <input name="title" placeholder-class="placeholder" placeholder="在此輸入標題" value="{{note.title}}" /> </view> <view class='row' id="textareawrap" catchtap="onFocus"> <textarea fixed="true" class='text' value="{{note.content}}" maxlength="5000" focus='{{focus}}' name="content" placeholder="點選新增文字" /> </view> <view class='bottom'> <button formType="submit" class='btn success'>儲存</button> <button class='btn del' bindtap="onDelete">刪除</button> </view> </view> </form>
再來看wxss
page{ width: 100%; height: 100%; } .container{ flex-flow:column nowrap; justify-content: center; align-items: center; width: 100%; height: 100%; background-color: #ffffff; display: flex; } .title{ margin: 15rpx 5%; width: 90%; text-align: left; height: 60rpx; font-size: 38rpx; border-bottom: 1px solid #f5f5f5; } .row{ flex: 1; display: flex; width: 90%; height:100%; margin: 0 5%; overflow: hidden; } .row .text{ flex: 1; width: 100%; height: 100%;//<----這裡是重點,textarea的高度 font-size: 16px; line-height: 26px; color: #000000; } .date{ padding: 5rpx 0; } .bottom{ width: 100%; background: #fafafa; display: flex; flex-flow:row nowrap; justify-content: center; align-items: center; border-top:1px solid #d9d9d9; } .bottom .btn{ flex: 1; line-height: 2; padding-top: 10rpx; padding-bottom: 10rpx; margin: 30rpx 30rpx; } .btn.success{ background: #1aad19; color: #fff; } .btn.del{ background: #e64340; color: #fff; }
把上面程式碼寫好,在電腦上編譯,執行,模擬器裡效果完美
但是,但是。。。
在真機上
textarea的內容已經超出了實際區域,而且此時操作“儲存”或“刪除”按鈕也是沒有任何作用,被textarea擋住了
檢視官方文件 https://developers.weixin.qq.com/miniprogram/dev/component/textarea.html
有這麼一句說明
tip
:textarea
元件是由客戶端建立的原生元件,它的層級是最高的,不能通過 z-index 控制層級。
原來是被渲染成原生元件
上面wxss中定義的height:100%; 不是填充滿所在view的空間,而是整個page的空間
所以這裡只能給textarea定義固定高度比較 height:300px; 這樣修改後內容超出的問題解決了
但這樣的效果又不太好,中間的區域留有一大段空白,我們需要動態的設定textarea高度
幸好有 wx.createSelectorQuery()介面
使用這個介面就可以獲取中間view的高度,把這個view的高度設定給textarea就可以了
js程式碼如下
Page({
data: {
note: {
id: "",
title: "",
summary: "",
content: "",
createTime: "",
updateTime: "",
isDelete: 0
},
isNew: false,
focus: false,
height:"" //data裡面增加height屬性
},
/**
* 頁面渲染事件
*/
onShow: function() {
var that = this;
let id = "#textareawrap";
let query = wx.createSelectorQuery();//建立查詢物件
query.select(id).boundingClientRect();//獲取view的邊界及位置資訊
query.exec(function (res) {
that.setData({
height: res[0].height + "px"
});
});
}
});
wxml程式碼修改如下:
<textarea fixed="true" class='text' value="{{note.content}}" maxlength="5000" style="height:{{height}}"
focus='{{focus}}'
name="content" placeholder="點選新增文字" />
在textarea裡面增加 style="height:{{height}}" 動態設定高度
結果符合預期
有興趣的朋友同學可以掃描二維碼體驗一下這個簡單的筆記本,多多支援!