You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不使用span标签的情况下实现textarea多色占位符文本?

关于textarea占位符局部文字变色的问题解答

不行,原生HTML/CSS无法实现给textarea占位符的部分文字单独设置颜色,且不使用span标签的话更没有可行方案

原因说明

  • textarea的placeholder属性是纯文本内容,不支持内嵌任何样式语法
  • CSS的::placeholder伪元素只能对整个占位符文本应用统一样式,无法拆分局部文本设置不同颜色

替代实现方案(模拟占位符)

如果一定要实现局部文字变色,可以放弃原生placeholder,用模拟元素来实现,具体代码如下:

HTML结构

<div class="textarea-container">
  <textarea id="colour" rows="9" name="message"></textarea>
  <div class="simulated-placeholder">
    <span style="color: #008000;">Hi</span>, I'm the next star architect! Here's my work before ever studying for a RIBA1, I first got inspired into doing architecture playing <span style="color: #ffff00;">Sims 4</span> and I instantly had to download Architecture software to build a house. My first project is my Mesuem/Art gallery and I grown massively in that first project. Please look though every project, especially the ones with the star. ... ...Also type here and hit send if you want to email me.
  </div>
</div>

CSS样式

.textarea-container {
  position: relative;
  display: inline-block;
}

.simulated-placeholder {
  position: absolute;
  top: 0.5em;
  left: 0.5em;
  color: #999; /* 匹配原生占位符默认灰色 */
  pointer-events: none; /* 允许点击穿透到下方textarea */
  white-space: pre-wrap; /* 保留文本换行,和textarea行为一致 */
}

/* 当textarea获得焦点或有内容时,隐藏模拟占位符 */
#colour:focus + .simulated-placeholder,
#colour:not(:placeholder-shown) + .simulated-placeholder {
  display: none;
}

内容的提问来源于stack exchange,提问作者Dan Palasz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 15:05:34