输入框的样子
文本域的样子
当输入框出现滚动条的时候,就自动切换成文本域;当文本域到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加光标显示宽度,但是实际上按照实际数据来会出很大偏差,所以我自己检测了一下,最后才定下适合我的数据。
这个终究是估算的,所有多少会有些偏差,我目前也没找到其他方法,所以最终还是需要你们自行结合实际情况。