應產品要求,實現輸入框換行功能,但是傳統的input不支持換行操作,故而使用其他方式進行實現。
方式一:contenteditable屬性的使用
使用一個div,<div contenteditable="true" id="t"></div>
但是存在問題是如果配合vue的雙向綁定會報錯
方式二:使用textarea進行模擬,監聽內容變化,動態改變其高度
html:
<textarea class="input-item textarea-item" placeholder="請輸入詳細地址" rows="1" ref="address" @focus="showClearBtn('AddressDetail')" @blur="hideCleanBtn('AddressDetail')" v-model="resObj.address_detail"> </textarea>
JS:
watch: { 'resObj.address_detail': function (newVal) { this.getHeight(this.$refs.address) }, },
// 詳細地址輸入框高度
getHeight (el) {
this.timer = setTimeout(() => {
el.style.height = 'auto' // 必須設置為auto
el.style.height = (el.scrollHeight) + 'px'
}, 20)
},