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

實(shí)現(xiàn)效果

  • 當(dāng)可編輯區(qū)域內(nèi)容為空時(shí),顯示 data-placeholder 的提示文本(灰色);
  • 輸入內(nèi)容后,提示文本自動(dòng)隱藏;
  • 清空內(nèi)容(包括空格)后,提示文本重新顯示。
contenteditable="true" 的元素添加 placeholder 的交互.gif

源碼

<template>
  <div
    <div 
      ref="editRef" 
      class="edit-content" 
      contenteditable="true"
      data-placeholder="請(qǐng)?jiān)诖溯斎雰?nèi)容..."
    ></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 === '';
    // 通過(guò) CSS 類控制占位符顯隱(可選)
    editableElement.classList.toggle('empty', isEmpty);
  };

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

    // 初始狀態(tài)檢查
    handleInput();

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

  // 卸載時(shí)移除事件監(jiān)聽
  onUnmounted(() => {
    editRef.value?.removeEventListener('input', handleInput);
  });
</script>

<style scoped lang="less">
  .edit-content {
    /* 默認(rèn)樣式 */
    min-height: 200px;
    padding: 10px;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    position: relative;

    /* 占位符樣式(內(nèi)容為空時(shí)顯示) */
    &.empty::before {
      content: attr(data-placeholder); /* 讀取 data-placeholder 內(nèi)容 */
      position: absolute;
      left: 10px;
      right: 10px;
      top: 10px;
      color: #bfbfbf; /* 灰色提示 */
      pointer-events: none; /* 防止點(diǎn)擊選中提示文本 */
    }
  }
</style>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容