用div+css实现聊天输入框,可输入、展示图片

 

 


<div class="dzm-textarea" id="dzm-textarea" contenteditable="true" @keypress="onKeypress" placeholder="输入文本" style="overflow: auto;"></div>
const onKeypress = (e)=> {
  if (e.key === 'Enter') {
    if (e.shiftKey) {
      // Shift+Enter 按下,执行换行
      initRange()
    } else {
      // 单纯的 Enter 按下,执行发送
      handleSend()
    }
    e.preventDefault()
  }
}
const initRange = ()=> {
  const inputDiv = document.querySelector("#dzm-textarea");
  inputDiv.innerText += "\n";
  const lastChild = inputDiv.lastChild;
  lastChild.innerText += "\n";
  const selection = window.getSelection();
  // 创建range对象
  const range = document.createRange();
  // 设置range的起始位置为div内容的第3个字符之后
  range.setStart(lastChild, lastChild.length);
  // 将range设置为选区
  selection.removeAllRanges();
  selection.addRange(range);
}
/* 输入框 */
.dzm-textarea {
flex: 1;
padding: 5px;
font-size: 14px;
max-height: 62px;
//border: 1px solid red;
}
/* 输入框为空时显示 placeholder */
.dzm-textarea:empty:before {
content: attr(placeholder);
color: rgb(200,200,200);
}
/* 输入框获取焦点时移除 placeholder */
.dzm-textarea:focus:before {
content: none;
}
posted @ 2023-08-30 17:23  尹言覃少  阅读(243)  评论(0编辑  收藏  举报