輸入框的樣子?
文本域的樣子
當輸入框出現滾動條的時候,就自動切換成文本域;當文本域到1行并且寬度小于輸入框寬度時切換成輸入框
<div class="left_box_inpt"><divclass="right_box_inpt":class="{notclickable: inputdisabled,}">//文本域<divv-if="isOverflow"style="display: flex;width: 98%;margin: 10px auto 0;border-radius: 25px !important;background-color: #fff;"><el-inputref="inputRef"id="text-input"v-model="memory"@input="oninput"@keyup.enter.native="sub()"type="textarea"resize="none":autosize="{ minRows: 1, maxRows: 4 }":style="{ width: textareawidth + 'px' }"></el-input></div>// 輸入框<divstyle="display: flex;width: 100%;border-radius: 25px !important;background-color: #fff;"><el-inputv-if="!isOverflow"ref="inputRef"id="text-input"v-model="memory"@input="oninput"@keyup.enter.native="sub()":disabled="inputdisabled"></el-input><divstyle="display: flex;line-height: 50px;padding: 0 10px;margin-left: auto;"><el-tooltipclass="item"effect="dark":content="$t('upload')"placement="top"><el-uploadref="upload"action="#"multiple:http-request="httpRequest":before-upload="beforeUpload":show-file-list="false"accept=".pdf,.docx,.xlsx"><el-buttonclass="subbtn"type="text"style="padding: 17px 0"icon="el-icon-circle-plus-outline":disabled="inputdisabled"></el-button></el-upload></el-tooltip><spanstyle="width: 1px;height: 15px;background-color: #dcdfe6;margin: auto 10px;"></span><el-tooltipclass="item"effect="dark":content="$t('send')"placement="top"><el-button:disabled="BtnDisabled"class="subbtn"type="text"@click="sub()"><imgv-if="BtnDisabled"src="@/assets/right1.png"style="width: 15px"/><imgv-elsesrc="@/assets/right3.png"style="width: 15px"/></el-button></el-tooltip></div></div></div></div>
<script>
export default {data () {return {memory: "", //發送信息BtnDisabled :false,isOverflow: false,//切換輸入框為文本框inputoffsetWidth: "",//輸入框的寬度textareawidth: "100%"//文本域的寬度};},methods: {// 監聽輸入框oninput (e) {if (e !== "") {this.BtnDisabled = false;} else {this.BtnDisabled = true;}// 輸入框超出變成文本框this.$nextTick(() => {const inputInner = this.$refs.inputRef.$el.querySelector('.el-input__inner');const textareaInner = this.$refs.inputRef.$el.querySelector('.el-textarea__inner');if (inputInner) {this.isOverflow = inputInner.scrollWidth > inputInner.offsetWidth;this.inputoffsetWidth = inputInner.offsetWidthsetTimeout(() => {this.$refs.inputRef.focus()}, 100)}if (textareaInner) {// 是不是1行if (textareaInner.scrollHeight < 52) {// 改變寬度this.textareawidth = this.getBLen(e) * 7 + 35if (this.textareawidth < this.inputoffsetWidth) {this.isOverflow = false;setTimeout(() => {this.$refs.inputRef.focus()this.textareawidth = '100%'}, 100)}}}});},// 獲取字符串的字節長度,中文2個、英文1個getBLen (str) {if (str == null) return 0;if (typeof str != "string") {str += "";}return str.replace(/[^\x00-\xff]/g, "01").length;},}
}
</script>
this.getBLen(e) * 7 + 35? ? ? 這個應該是字符串長度乘以字體px加光標顯示寬度,但是實際上按照實際數據來會出很大偏差,所以我自己檢測了一下,最后才定下適合我的數據。
這個終究是估算的,所有多少會有些偏差,我目前也沒找到其他方法,所以最終還是需要你們自行結合實際情況。