contenteditable="true" 的元素添加 placeholder 的交互

实现效果

  • 当可编辑区域内容为空时,显示 data-placeholder 的提示文本(灰色);
  • 输入内容后,提示文本自动隐藏;
  • 清空内容(包括空格)后,提示文本重新显示。
contenteditable="true" 的元素添加 placeholder 的交互.gif

源码

<template>
  <div
    <div 
      ref="editRef" 
      class="edit-content" 
      contenteditable="true"
      data-placeholder="请在此输入内容..."
    ></div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onUnmounted } from 'vue';
  
  const editRef = ref<HTMLDivElement>(null);

  const handleInput = () => {
    const editableElement = editRef.value;
    if (!editableElement) return;

    const isEmpty = editableElement.textContent === '';
    // 通过 CSS 类控制占位符显隐(可选)
    editableElement.classList.toggle('empty', isEmpty);
  };

  onMounted(() => {
    editRef.value?.addEventListener('input', handleInput);

    // 初始状态检查
    handleInput();

    editRef.value?.focus();
  });

  // 卸载时移除事件监听
  onUnmounted(() => {
    editRef.value?.removeEventListener('input', handleInput);
  });
</script>

<style scoped lang="less">
  .edit-content {
    /* 默认样式 */
    min-height: 200px;
    padding: 10px;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    position: relative;

    /* 占位符样式(内容为空时显示) */
    &.empty::before {
      content: attr(data-placeholder); /* 读取 data-placeholder 内容 */
      position: absolute;
      left: 10px;
      right: 10px;
      top: 10px;
      color: #bfbfbf; /* 灰色提示 */
      pointer-events: none; /* 防止点击选中提示文本 */
    }
  }
</style>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容