---
title: textArea的placeholder不能换行的解决方案
date: 2013-10-11T12:49:35.000Z
updated: 2015-01-09T05:08:16.000Z
tags:
  - article
---

_JS解决方案当然是最万能的。_
所以这里主要讲的是CSS解决方案，整理自鬼懿IT高级群的讨论 _10-11-2013_。
先上一段官方的说辞：

> The placeholder attribute represents a short hint (a word or short phrase) intended to aid the user with data entry. A hint could be a sample value or a brief description of the expected format. The attribute, if specified, must have a value that contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters.

## 1

首先要知道的是HTML属性中的值会原封不动地输出到页面中，所以：

```html
<textarea
  placeholder="line1  \n lin2 <br> line3 \A line4 
line5"
></textarea>
```

是不会其任何作用的（这里line4和line5中的回车写法会被过滤掉，但是title属性就不会）。
所以就要借用到CSS。

## 2

先说webkit浏览器的解决方案：
首先要知道placeholder属性是可以用css来操作的，设置字体颜色、字体大小等等等。
（相关文章：[HTML5 Placeholder Styling with CSS](http://davidwalsh.name/html5-placeholder-css)）
所以我们就可以用after伪类来实现把placeholder内容写到CSS中，这样就绕开了HTML属性的渲染方案：

```css
textarea::-webkit-input-placeholder:after {
  content: "line@ \A line#"; /* 这里 \A 形成回车符号  */
  color: red;
}
```

## 3

在兼容性写法中，不同浏览器的标示要分开来写，否则使解析器混淆CSS语义：

```css
/* 错误写法 */
input::-webkit-input-placeholder,
input:-moz-placeholder {
}
```

```css
/* 正确写法 */
input::-webkit-input-placeholder {
}

input:-moz-placeholder {
}
```

## 4

然而群里面还对此提出一个观点，就是不应该在CSS中写应该在HTML中写的内容：

> 多语言的应用，这样还得连css也加入翻译转换
> (js)不太靠谱，css这东西顺序有关，你知道插哪儿啊
>
> > 240

总之，这种绕着弯子完成的解决方案本身就有缺陷，毕竟没有那么多空子给你转。

## 5

另外，通过 **计算空格** 来让placeholder自动换行也是个比较恶心的解决方案。但精力上绝对比较省，需要些一个计算空格的函数，耦合度也不会像上面CSS解决方案那么高。

## 6

最后还有一个值得一提的就是下面这种无法生效的写法：

```html
<!-- placeholder属性必须存在且非空 -->
<textarea placeholder=" " data-placeholder="\A  line2"></textarea>
```

```css
textarea::-webkit-input-placeholder:after {
  content: "line1" attr(data-placeholder) "\A  line3";
  color: red;
}
```

这里无法获取到data-placeholder属性的值，因为双伪类导致`:after`的对象不是textarea，而是`placeholder`（shadow DOM）。

最后给出stackoverflow上[相关的问题及其解答](http://stackoverflow.com/questions/7189223/can-you-have-multiline-html5-placeholder-text-in-a-textarea)，涉及到更多详细的内容，值得一读。
