核心代码

  • 使用contenteditable="true"属性
<div data-v-b0c64392=""
contenteditable="true"
spellcheck="false"
placeholder="输入评论..."
class="rich-input"></div>
  • 设置最小高度
min-height: 24px;

完整代码实现

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.rich-input[data-v-b0c64392] {
position: relative;
font-size: 14px;
line-height: 1.7;
color: #17181a;
outline: none;
min-height: 24px;
background-color: #fff;
border: 1px solid #f1f1f1;
border-radius: 3px;
}
</style>
</head>
<body>
<div data-v-b0c64392=""
contenteditable="true"
spellcheck="false"
placeholder="输入评论..."
class="rich-input"></div>
</body>
</html>

在线运行示例

​https://jsfiddle.net/000000/xpq619vy/​

遇到的问题

在移动端的时候经常用到fastclick库导致touch无法聚焦。我们使用

.needsclick {
content: attr(placeholder);
color: #B8B8B8;
}

<div contentEditable="true" class="needsclick" placeholder="请输入详细地址"></div>

这样就可以聚焦了。添加neecsclick类。

原理

  • 原因

Fastclick在touchend事件触发时使用document.createEvent触发click事件来解决click在移动端的延迟,同时拦截原生的click事件。这样div就获取不到原生的click事件,focus也失效。这也是为什么pc端没问题,因为pc端没有touch事件

  • 解决办法

官方文档有说明

Advanced
Ignore certain elements with needsclick
Sometimes you need FastClick to ignore certain elements. You can do this easily by adding the needsclick class.

<a class="needsclick">Ignored by FastClick</a>