CSS【实战】可编辑元素实现 placeholder -- contenteditable=“true“

效果


技术要点

HTML 中,placeholder 属性原生支持 <input> 和 <textarea> 等表单元素,但对于可编辑元素(如 contenteditable="true" 的普通元素),需要通过CSS 实现类似 placeholder 的效果。

  • 利用 CSS 伪类 :empty 检测元素是否为空
  • 使用 ::before 伪元素显示占位文本
  • 结合 :focus 伪类在元素获得焦点时隐藏占位文本

代码

html 复制代码
<script setup lang="ts"></script>

<template>
  <div
    class="editable box"
    contenteditable="true"
    data-placeholder="请输入内容..."
  ></div>
</template>
<style scoped>
.box {
  min-height: 80px;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  outline: none;
  transition: border-color 0.2s;
}

.box:focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
}
/* 占位文本样式 */
.editable:empty::before {
  content: attr(data-placeholder);
  color: #9ca3af;
  pointer-events: none; /* 点击时不触发伪元素 */
}

/* 聚焦时隐藏占位文本 */
.editable:focus:empty::before {
  content: "";
}
</style>
相关推荐
金八梭6 天前
格斗对决v4.5
前端·css·自动化·html·css3
CappuccinoRose8 天前
前端开发交互体系 - 汇总篇
开发语言·前端·javascript·css·html·交互
inksci10 天前
用飞帆做了个小网页
前端·javascript·css·html
星云_byto10 天前
CSS面试题
前端·css
科研邪修法11 天前
PDF新增页面文字与文本批注怎么区分?以双版本培训讲义为例
前端·css·pdf
狮子座的男孩11 天前
html+css基础:31、响应式布局(媒体类型,媒体特性,运算符,常用阈值)
前端·css·经验分享·html·响应式布局·媒体类型/特性·常用阈值
狮子座的男孩11 天前
html+css基础:32、BFC(父子元素防止 margin 塌陷,父子元素清除浮动,兄弟元素两栏布局)
前端·css·经验分享·html·bfc·margin塌陷·清除浮动
吴长建先生12 天前
Flutter IM 即时聊天应用开发:从 0 到 1 实
css
htzyl20613 天前
前端样式-弹窗淡入淡出,为什么你的 `transition` 一直不生效
前端·css·html
Brookty13 天前
CSS基础知识(二):盒模型、内外边距、外边距折叠与父子元素的布局关系
前端·css