1、前言

在正在做的后台项目中,有一个需求要求如下

  1. 输入文本内容
  2. 支持插入参数,参数系统提供
  3. 限定500字符,超过则输入无效,限制不让输入

大概效果图:
image.png
image.png

2、分解思考

  1. 从布局来看,

3、问题

1、回车只想产生 br 不想产生默认的 divp 标签 怎么办?

谷歌: 给 contenteditable 元素设置 inner-block 就可以

IE :需要写一个获取内部文本的

2、富文本 placeholder 使用 css 如何实现

答:可以使用 CSS3 的 attr 函数拿到由父级组件传进来的 placeholder
代码:

  1. // 父组件引用
  2. <template>
  3. <div>
  4. <TextContent placeholder="请输入内容" />
  5. </div>
  6. </template>
  7. // 子组件
  8. <template>
  9. <div class="textContent">
  10. <label
  11. class="textContent_label"
  12. :class="[isRequire&&'common_require']"
  13. v-if="label"
  14. >
  15. {{ label }}
  16. </label>
  17. <div class="textContent_box" :style="{width,height}">
  18. <pre
  19. class="textContent_box_edit"
  20. :placeholder="placeholder"
  21. :contenteditable="!isReadonly"
  22. ref="TextContent"
  23. @click="editClick"
  24. @keydown="keyDown"
  25. @keyup="setLastRange"
  26. @paste="paste"
  27. ></pre>
  28. <span class="textContent_box_tips">
  29. {{ model.length}} / {{ maxlength}}
  30. </span>
  31. </div>
  32. </div>
  33. </template>
  34. // 部分的样式
  35. <style lang="less">
  36. ...
  37. .textContent_box{
  38. &_edit{
  39. width: 100%;
  40. height: 100%;
  41. outline: none;
  42. border-radius: 5px;
  43. overflow-y: auto;
  44. word-break: break-all;
  45. white-space: pre-wrap;
  46. display: inline-block;
  47. &:empty {
  48. // 之所以使用 :not(:focus) 选择器,是因为在 IE 浏览器上,鼠标选中的时候,光标会在
  49. // placeholder后面,并且不会消失
  50. &:not(:focus) {
  51. &::before {
  52. content: attr(placeholder);
  53. color: #C0C4CC;
  54. }
  55. }
  56. }
  57. }
  58. }
  59. </style>

3、遇到复制粘贴怎么处理?

由于复制的内容千奇百怪,可我们只想对应的文字,那么可以使用 粘贴事件 clipboardData

  • 粘贴事件有一个 clipboardData的属性,提供了对剪贴板的访问
  • clipboardDatagetData(fomat) 从剪贴板获取指定格式的数据
  • fomat 在谷歌浏览器中是 text/plain、text ,但是 IE 只支持 text
  • event.originalEvent 指向原始的事件对象
  • IEclipboardData对象是在 window对象中,并不是在 event 事件对象中
    1. paste(event) {
    2. const clipboardData =(event.originalEvent || event).clipboardData ||window.clipboardData;
    3. let text = clipboardData.getData("text") || '';
    4. }