vue页面内使用
html
<el-input
:disabled="inputdisabled"
ref="inputRef"
id="text-input"
v-model="messinput"
@keydown.native="Keydown"
placeholder="请输入您的问题,可通过Ctrl+回车换行"
type="textarea"
resize="none"
:autosize="{ minRows: 1, maxRows: 4 }"
></el-input>
javascript
// 回车发送(shift+回车换行,浏览器默认,ctrl+回车换行)
Keydown (event) {
// 回车发送
if (!event.ctrlKey && !event.shiftKey && event.keyCode == 13) {
event.cancelBubble = true; //ie阻止冒泡行为
event.stopPropagation();//Firefox阻止冒泡行为
event.preventDefault(); //取消事件的默认动作*换行
//以下处理发送消息代码
if (!this.BtnDisabled) {
this.sub()
}
} else if (event.key === 'Enter' && event.shiftKey) {
// shift+回车换行禁用
event.cancelBubble = true; //ie阻止冒泡行为
event.stopPropagation();//Firefox阻止冒泡行为
event.preventDefault(); //取消事件的默认动作*换行
} else if (event.key === 'Enter' && event.ctrlKey) {
// ctrl+回车换行
event.preventDefault(); // 阻止默认的换行行为
const selectionStart = event.target.selectionStart; // 获取光标位置
this.messinput = this.messinput.substring(0, selectionStart) + '\n' + this.messinput.substring(selectionStart);
// 重设光标位置
this.$nextTick(() => {
event.target.selectionStart = selectionStart + 1;
event.target.selectionEnd = selectionStart + 1;
});
}
},
js原生
html
<textarea class="custom" id='text-area' placeholder="输入消息..." value='' rows=2 ></textarea>
javascript
document
.getElementById("text-area")
.addEventListener("keydown", function (event) {
// 回车发送
if (!event.ctrlKey && !event.shiftKey && event.keyCode == 13) {
event.cancelBubble = true; //ie阻止冒泡行为
event.stopPropagation(); //Firefox阻止冒泡行为
event.preventDefault(); //取消事件的默认动作*换行
//以下处理发送消息代码
if (!messageInput.disabled) {
sendMessage();
}
} else if (event.key === "Enter" && event.shiftKey) {
// shift+回车换行禁用
event.cancelBubble = true; //ie阻止冒泡行为
event.stopPropagation(); //Firefox阻止冒泡行为
event.preventDefault(); //取消事件的默认动作*换行
} else if (event.key === "Enter" && event.ctrlKey) {
// ctrl+回车换行
event.preventDefault(); // 阻止默认的换行行为
let textarea = document.getElementById("text-area");
let cursorPos = textarea.selectionStart;
let v = textarea.value;
let textBefore = v.substring(0, cursorPos);
let textAfter = v.substring(cursorPos, v.length);
textarea.value = textBefore + "\n" + textAfter;
textarea.selectionStart = cursorPos + 1;
textarea.selectionEnd = cursorPos + 1;
}
});