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>
相关推荐
WebGirl3 小时前
一个 CSS 属性aspect-ratio
css
xump4 小时前
如何在DevTools选中调试一个实时交互才能显示的元素样式
前端·javascript·css
Lhuu(重开版10 小时前
CSS:动效布局动画
前端·css
不羁的fang少年13 小时前
前端常见问题(vue,css,html,js等)
前端·javascript·css
yivifu13 小时前
CSS Grid 布局详解(2025最新标准)
前端·css
姜太小白15 小时前
【前端】CSS媒体查询响应式设计详解:@media (max-width: 600px) {……}
前端·css·媒体
蓝胖子的多啦A梦17 小时前
ElementUI表格错位修复技巧
前端·css·vue.js·el-table表格错位
喂自己代言18 小时前
HTML ``元素:链接外部资源的关键角色与用法
css·html
猴猴不是猴18 小时前
js实现卷轴,中间可滑动方块,左右两侧对比
javascript·css·css3
y***866919 小时前
前端CSS-in-JS方案
前端·javascript·css