如何制作可扩展的聊天输入表单

时间:2019-05-11 07:27:41

标签: javascript html css

我一直在寻找一种方法来像在现代聊天应用程序中一样垂直扩展文本输入表单。

每个人都说我们应该使用textarea,因为表单输入不允许多行,但是松弛和频谱使用的是表单...(虽然不一致,但使用text-area)

我想从一行开始,当用户输入换行符(shift + enter)时,输入将扩展到顶部。

.chat-footer {
  display: grid;
  grid-template-rows: 90vh max-content;
  height: 100%;
  background-color: var(--color-i-bg);
  grid-area: i;
  border-top: 1px solid #ddd;
  border-top: var(--color-i-border-top);
  padding-bottom: 1rem;
}
.chat-footer__form {
  align-self: end;
  display: grid;
  grid-row: 2 / 3;
  grid-template-columns: 1fr max-content;
  width: 100%;
  height: 100%;
  vertical-align: middle;
  white-space: normal;
  background: none;
  line-height: 1;
}
.chat-footer__form::placeholder {
  color: lightgrey;
  font-size: 1em;
}
.chat-footer__form-container-input {
  grid-column: 1/2;
}
.chat-footer__form-container-btn {
  grid-column: 2/3;
}
.chat-footer__form-input {
  width: 100%;
  height: 100%;
}
.chat-footer__form * > button {
  background-color: inherit;
  border: 0;
  line-height: normal;
}
.chat-footer__form * > button:hover {
  cursor: pointer;
}
.chat-footer__form * > button:focus, .chat-footer__form * > button:active {
  outline: 0;
}
 <div class="chat-footer">
        <form class="chat-footer__form" role="form">
            <div class="chat-footer__form-container-input">
                <input type="text" class="chat-footer__form-input" placeholder="New message">
            </div>
            <div class="chat-footer__form-container-btn">
                <button class="chat-footer__form-btn" id="form-attach">Attach</button>
                <button class="chat-footer__form-btn" id="form-smiley">Smiley</button>
            </div>
        </form>
    </div>

如果这是一个更好的解决方案,我不反对使用文本区域。

编辑---

最后,我将contenteditable =“ true”与overflow:auto;一起使用了解决方案。在我的主容器上,并将其用于占位符:

&[placeholder]:empty:not(:focus):before {
    content: attr(placeholder);
}

这成功了。谢谢大家的回答!

2 个答案:

答案 0 :(得分:1)

您可以有一个div(没有输入,没有文本区域),并使用contenteditable="true"属性:

<div contenteditable="true"></div>

现在,当用户单击div时,他们可以编写东西!就像输入一样。因此,您只需要侦听此div的事件,例如,当用户按下shift+enter时添加一个<br>标签或创建一些段落即可。

我检查了松弛输入,他们使用了相同的技术。您可能还需要使用其他一些属性:

 autocomplete="off" autocorrect="off" spellcheck="true" aria-expanded="false" aria-autocomplete="list" aria-multiline="true" aria-label="Message" dir="auto" contenteditable="true" role="textbox"

答案 1 :(得分:0)

要从下往上扩展输入,请执行以下操作:

.chat-footer__form-container-input {
  position: relative;
}
.chat-footer__form-input {
  position: absolute;
  bottom: 0;
}

要在shift + Enter上增长,我建议使用JS输入处理程序来进行textarea:

<textarea onkeypress="handleInput(event)" class="chat-footer__form-input" placeholder="New message"></textarea>

以一行的绝对单位设置其高度:

.chat-footer__form-input {
  width: 100%;
  height: 20px;
}

并使用shift + Enter行为设置脚本(只有Enter会提交表单):

function handleInput(e) {
  if(e.key=="Enter") {
    if(e.shiftKey) e.target.style.height = e.target.offsetHeight+20+"px";
    else e.target.form.submit();
  }
}