效果
技术要点
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>