在textarea的占位符属性中插入换行符?

时间:2022-11-19 03:00:25

I have tried a few approaches but none worked. Does anyone know a the nifty trick to get around this?

我尝试过几种方法,但没有一种有效。有人知道避开这个的妙招吗?

<textarea placeholder='This is a line \n this should be a new line'></textarea>

<textarea placeholder='This is a line     
should this be a new line?'></textarea> <!-- this works in chrome apparently -->

UPDATE: It doesn't work in chrome. It was just the textarea width.

更新:它在chrome不工作。它只是文本区域的宽度。

See: http://jsfiddle.net/pdXRx/

参见:http://jsfiddle.net/pdXRx/

17 个解决方案

#1


51  

What you could do is add the text as value, which respects the line break \n.

您可以做的是将文本添加为value,它尊重断行\n。

$('textarea').attr('value', 'This is a line \nthis should be a new line');

Then you could remove it on focus and apply it back (if empty) on blur. Something like this

然后你可以在焦点上移除它,在blur中应用它(如果是空的)。像这样的东西

var placeholder = 'This is a line \nthis should be a new line';
$('textarea').attr('value', placeholder);

$('textarea').focus(function(){
    if($(this).val() === placeholder){
        $(this).attr('value', '');
    }
});

$('textarea').blur(function(){
    if($(this).val() ===''){
        $(this).attr('value', placeholder);
    }    
});

Example: http://jsfiddle.net/airandfingers/pdXRx/247/

例如:http://jsfiddle.net/airandfingers/pdXRx/247/

Not pure CSS and not clean but does the trick.

不是纯CSS,也不干净,但是很有用。

#2


137  

You can insert a new line html entity &#10; inside the placeholder attribute:

您可以插入一个新的行html实体 在占位符属性:

<textarea name="foo" placeholder="hello you&#10;Second line&#10;Third line"></textarea>

< span style = ' font - size: 9.0 pt; font - family:宋体;mso - ascii - font - family:

Works on: Chrome 62, IE10

用于:Chrome 62, IE10

Doesn't work on: Firefox 57, Safari 11

不支持:Firefox 57, Safari 11

https://jsfiddle.net/lu1s/bxkjLpag/2/

https://jsfiddle.net/lu1s/bxkjLpag/2/

#3


53  

Don't think you're allowed to do that: http://www.w3.org/TR/html5/forms.html#the-placeholder-attribute

不要认为你可以这样做:http://www.w3.org/TR/html5/forms.html#占位符属性

The relevant content (emphasis mine):

相关内容(重点是我的):

The placeholder attribute represents a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value. 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.

占位符属性表示一个短提示(一个单词或短短语),当控件没有值时,该提示用于帮助用户输入数据。提示可以是示例值,也可以是预期格式的简要描述。如果指定该属性,则必须具有不包含U+000A行提要(LF)或U+000D节返回(CR)字符的值。

#4


46  

UPDATE (Jan 2016): The nice little hack might not work on all browsers anymore so I have a new solution with a tiny bit of javascript below.

更新(2016年1月):这个漂亮的小技巧可能不再适用于所有浏览器,所以我有了一个新的解决方案,下面有一小段javascript代码。


A Nice Little Hack

It doesn't feel nice, but you can just put the new lines in the html. Like this:

感觉不太好,但是你可以把新的行放到html中。是这样的:

<textarea rows="6" id="myAddress" type="text" placeholder="My Awesome House,
        1 Long St
        London
        Postcode
        UK"></textarea>

Notice each line is on a new line (not being wrapped) and each 'tab' indent is 4 spaces. Granted it is not a very nice method, but it seems to work:

注意每一行都在一条新行上(没有被包装),每个“标签”缩进是4个空格。虽然这不是一个很好的方法,但它似乎是有效的:

http://jsfiddle.net/01taylop/HDfju/

http://jsfiddle.net/01taylop/HDfju/

  • It is likely that the indent level of each line will vary depending on the width of your text area.
  • 很可能每行的缩进级别会根据文本区域的宽度而变化。
  • It is important to have resize: none; in the css so that the size of the textarea is fixed (See jsfiddle).
  • 调整大小很重要:无;在css中,使textarea的大小是固定的(参见jsfiddle)。

Alternatively When you want a new line, hit return twice (So there is a empty line between your 'new lines'. This 'empty line' created needs to have enough tabs/spaces that would equate to the width of your textarea. It doesn't seem to matter if you have far too many, you just need enough. This is so dirty though and probably not browser compliant. I wish there was an easier way!

或者,当你想要一个新的行时,点击回车两次(所以在你的“新行”之间有一个空行。这个“空行”创建需要有足够的选项卡/空格,这将等同于textarea的宽度。如果你有太多的东西,你只需要足够的。这太脏了,而且可能不兼容浏览器。我希望有更简单的方法!


A Better Solution

Check out the JSFiddle.

查看JSFiddle。

  • This solution positions a div behind the textarea.
  • 这个解决方案在文本区域后面放置一个div。
  • Some javascript is used to change the background colour of the textarea, hiding or revealing the placeholder appropriately.
  • 一些javascript用于更改文本区域的背景颜色,适当地隐藏或显示占位符。
  • The inputs and placeholders must have the same font sizes, hence the two mixins.
  • 输入和占位符必须具有相同的字体大小,因此有两个mixin。
  • The box-sizing and display: block properties on the textarea are important or the div behind it will not be the same size.
  • 方框大小和显示:在textarea上的块属性很重要,或者它后面的div不会是相同的大小。
  • Setting resize: vertical and a min-height on the textarea are also important - notice how the placeholder text will wrap and expanding the textarea will keep the white background. However, commenting out the resize property will cause issues when expanding the textarea horizontally.
  • 设置大小:垂直的和最小的高度也很重要——注意占位符文本将如何包装和展开文本区域将保持白色背景。但是,在水平扩展文本区域时,注释出resize属性将导致问题。
  • Just make sure the min-height on the textarea is enough to cover your entire placeholder at its smallest width.**
  • 只需确保textarea上的最小高度足够覆盖整个占位符的最小宽度。**

在textarea的占位符属性中插入换行符?

HTML:

HTML:

<form>
  <input type='text' placeholder='First Name' />
  <input type='text' placeholder='Last Name' />
  <div class='textarea-placeholder'>
    <textarea></textarea>
    <div>
      First Line
      <br /> Second Line
      <br /> Third Line
    </div>
  </div>
</form>

SCSS:

SCSS:

$input-padding: 4px;

@mixin input-font() {
  font-family: 'HelveticaNeue-Light', 'Helvetica Neue Light', 'Helvetica Neue', Helvetica, Arial, 'Lucida Grande', sans-serif;
  font-size: 12px;
  font-weight: 300;
  line-height: 16px;
}

@mixin placeholder-style() {
  color: #999;
  @include input-font();
}

* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

form {
  width: 250px;
}

input,textarea {
  display: block;
  width: 100%;
  padding: $input-padding;
  border: 1px solid #ccc;
}

input {
  margin-bottom: 10px;
  background-color: #fff;

  @include input-font();
}

textarea {
  min-height: 80px;
  resize: vertical;
  background-color: transparent;
  &.data-edits {
    background-color: #fff;
  }
}

.textarea-placeholder {
  position: relative;
  > div {
    position: absolute;
    z-index: -1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    padding: $input-padding;
    background-color: #fff;
    @include placeholder-style();
  }
}

::-webkit-input-placeholder {
  @include placeholder-style();
}
:-moz-placeholder {
  @include placeholder-style();
}
::-moz-placeholder {
  @include placeholder-style();
}
:-ms-input-placeholder {
  @include placeholder-style();
}

Javascript:

Javascript:

$("textarea").on('change keyup paste', function() {
  var length = $(this).val().length;
  if (length > 0) {
    $(this).addClass('data-edits');
  } else {
    $(this).removeClass('data-edits');
  }
});

#5


14  

How about a CSS solution: http://cssdeck.com/labs/07fwgrso

CSS解决方案:http://cssdeck.com/labs/07fwgrso ?

::-webkit-input-placeholder::before {
  content: "FIRST\000ASECOND\000ATHIRD";
}

::-moz-placeholder::before {
  content: "FIRST\000ASECOND\000ATHIRD";
}

:-ms-input-placeholder::before {
  content: "FIRST\000ASECOND\000ATHIRD";
}

#6


11  

Salaamun Alekum

Salaamun Alekum

&#10;

Works For Google Chrome

适用于谷歌浏览器

在textarea的占位符属性中插入换行符?

<textarea placeholder="Enter Choice#1 &#10;Enter Choice#2 &#10;Enter Choice#3"></textarea>

I Tested This On Windows 10.0 (Build 10240) And Google Chrome Version 47.0.2526.80 m

我在Windows 10.0 (Build 10240)和谷歌Chrome版本47.0.2526.80 m上进行了测试

08:43:08 AST 6 Rabi Al-Awwal, 1437 Thursday, 17 December 2015

2015年12月17日,星期四,东部时间8点43分08分

Thank You

谢谢你!

#7


7  

Nope you cant do that in the placeholder attribute. You cant even html encode newlines like &#13;&#10; in a placeholder.

不,在占位符属性中不能这样做。甚至连html都不能编码像#13;#10这样的换行在一个占位符。

A small demo:

一个小演示:

http://jsfiddle.net/pdXRx/5/

http://jsfiddle.net/pdXRx/5/

#8


5  

You can't do it with pure HTML, but this jQuery plugin will let you: https://github.com/bradjasper/jQuery-Placeholder-Newlines

你不能用纯HTML来做,但是这个jQuery插件会让你:https://github.com/bradjasper/jQuery-Placeholder-Newlines

#9


5  

Try this:

试试这个:

<textarea
placeholder="Line1&#x0a;&#x09;&#x09;&#x09;Line2"
cols="10"
rows="5"
style="resize:none">
</textarea>

http://jsfiddle.net/vr79B/

http://jsfiddle.net/vr79B/

#10


4  

A slightly improved version of the Jason Gennaro's answer (see code comments):

杰森·杰纳罗的回答稍有改进(参见代码注释):

var placeholder = 'This is a line \nthis should be a new line';
$('textarea').attr('value', placeholder);
$('textarea').focus(function(){
    if($(this).val() == placeholder){
        // reset the value only if it equals the initial one    
        $(this).attr('value', '');
    }
});
$('textarea').blur(function(){
    if($(this).val() == ''){
        $(this).attr('value', placeholder);
    }    
});
// remove the focus, if it is on by default
$('textarea').blur();

#11


4  

I liked the work of Jason Gennaro and Denis Golomazov, but I wanted something that would be more globally useful. I have modified the concept so that it can be added to any page without repercussion.

我喜欢杰森·杰纳罗(Jason Gennaro)和丹尼斯·戈罗马佐夫(Denis Golomazov)的作品,但我想要的是更具有全球意义的作品。我已经修改了这个概念,这样它就可以添加到任何页面而不产生任何影响。

http://jsfiddle.net/pdXRx/297/

http://jsfiddle.net/pdXRx/297/

<h1>Demo: 5 different textarea placeholder behaviors from a single JS</h1>

<h2>Modified behaviors</h2>

<!-- To get simulated placeholder with New Lines behavior,
     add the placeholdernl attribute -->

<textarea placeholdernl>    (click me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<textarea placeholder='Address' placeholdernl>    (click me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<h2>Standard behaviors</h2>

<textarea placeholder='Address'>    (delete me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<textarea>    (delete me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<textarea placeholder='Address'></textarea>

The javascript is very simple

javascript非常简单

<script>
(function($){
var handleFocus = function(){
    var $this = $(this);
    if($this.val() === $this.attr('placeholdernl')){
        $this.attr('value', '');
        $this.css('color', '');
    }
};

var handleBlur = function(){
    var $this = $(this);
    if($this.val() == ''){
        $this.attr('value', $this.attr('placeholdernl'))
        $this.css('color', 'gray');
    }    
};

$('textarea[placeholdernl]').each(function(){
    var $this = $(this),
        value = $this.attr('value'),
        placeholder = $this.attr('placeholder');
    $this.attr('placeholdernl', value ? value : placeholder);
    $this.attr('value', '');
    $this.focus(handleFocus).blur(handleBlur).trigger('blur');
});
})(jQuery);
</script>

#12


4  

Use &#10; in place of /n this will change the line.

使用& # 10;代替/n,这将改变直线。

#13


2  

I modified @Richard Bronosky's fiddle like this.

我修改了@Richard Bronosky的小提琴。

It's better approach to use data-* attribute rather than a custom attribute. I replaced <textarea placeholdernl> to <textarea data-placeholder> and some other styles as well.

使用data-*属性比使用自定义属性更好。我将

edited
Here is the Richard's original answer which contains full code snippet.

这里编辑的是Richard的原始答案,其中包含完整的代码片段。

#14


2  

HTML

<textarea data-placeholder="1111\n2222"></textarea>

JS

$('textarea[data-placeholder]').each(function(){
    var $this = $(this),
        placeholder = $this.data('placeholder'),
        placeholderSplit = placeholder.split('\\n');
    placeholder = placeholderSplit.join('\n');
    $this.focus(function(){
        var $this = $(this);
        if($this.val() === placeholder){
            $this.val('');
            // $this.removeClass('placeholder');
        }
    }).blur(function(){
        var $this = $(this);
        if($this.val() == '') {
            $this.val(placeholder);
            // $this.addClass('placeholder');
        }
    }).trigger('blur');
});

#15


1  

very simple

非常简单的

  var position = your break position;
    var breakLine = "&#13;&#10;";//in html 
    var output = [value.slice(0, position), breakLine, value.slice(position)].join('');
    return output;

value represent the original string

值表示原始字符串

#16


1  

Check out this solution with custom placeholder.

使用自定义占位符检查此解决方案。

  • You get multiline placeholder that works in all browsers (including Firefox)
  • 在所有浏览器(包括Firefox)中都可以使用多行占位符
  • It is posible to customise placeholder as you want
  • 可以根据需要定制占位符

Demo on fiddle.

在小提琴的演示。

$(document).on('input', '#textArea', function () {
	
        if ($('#textArea').val()) {
            $('#placeholderDiv').hide();
        } else {
            $('#placeholderDiv').show();
        }   
});
#textAreaWrap {
    position: relative;
    background-color: white;
}

#textArea {
    position: relative;
    z-index: 1;
    width: 350px;
    height: 100px;
    min-height: 100px;
    padding: 6px 12px;
    resize: vertical;
    background-color: transparent;
    /* When set background-color: transparent - Firefox  displays
    unpleasant textarea border. Set border style to fix it.*/
    border: 1px solid #a5a5a5;
}

#placeholderDiv {
    position: absolute;
    top: 0;
    padding: 6px 13px;
    color: #a5a5a5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="textAreaWrap">
    
<textarea id="textArea"></textarea>

<!-- Check here. If textarea has content -
     set for this div attribute style="display: none;" -->
<div id="placeholderDiv">Multiline textarea<br>
                         placeholder<br>
                         <br>
                         that works in Firefox</div>
    
</div>

#17


0  

I don't like hiding the placeholder when you focus the textarea. So I made a constructor function Placeholder that looks exactly like the built-in placeholder and works also in other browsers than Google Chrome. It's very convenient because you can use the Placeholder function as often as you want and it doesn't even need jQuery.

我不喜欢隐藏占位符当你聚焦文本区域。因此,我创建了一个构造函数占位符,它看起来完全像内置的占位符,在其他浏览器中也比谷歌Chrome更有效。它非常方便,因为您可以随时使用占位符函数,甚至不需要jQuery。

EDIT:

编辑:

It now also handles special cases, like inserting the placeholder, correctly.

它现在还可以正确地处理特殊情况,如插入占位符。

var textarea = document.getElementById("textarea");
new Placeholder(textarea, "Line 1\nLine 2\nLine 3");

function Placeholder(el, placeholder) {
    if (el.value == "" || el.value == placeholder) {
        el.style.color = "gray";
        el.value = placeholder;
        el._plc = true;
        el.className += " unselectable";
    }
    function keyPress(e) {
        window.setTimeout(function() {
            var replaced = reverseStr(el.value).replace(reverseStr(placeholder), "");
            
            if (el.value == "") {
                el.value = placeholder;
                el.style.color = "gray";
                cursorToStart(el);
                el._plc = true;
                el.className += " unselectable";
            } else if (el._plc && el.value.endsWith(placeholder) && replaced !== "") {
                el.value = reverseStr(replaced);
                el.style.color = "black";
                el._plc = false;
                el.readOnly = false;
                el.className = el.className.replace("unselectable", "");
            } else if (el._plc && el.readOnly) {
                var ch = String.fromCharCode(e.charCode);
                if (e.keyCode == 13) ch = "\n";     // ENTER
                else if (e.charCode == 0) return;   // non-character keys
                
                el.value = ch;
                el.style.color = "black";
                el._plc = false;
                el.readOnly = false;
                el.className = el.className.replace("unselectable", "");
            }
        }, 10);
    }
    el.addEventListener("keypress", keyPress, false);
    el.addEventListener("paste", keyPress, false);
    el.addEventListener("cut", keyPress, false);
    el.addEventListener("mousedown", function() {
        if (el._plc) el.readOnly = true;
    }, false);
    el.addEventListener("mouseup", function() {
        el.readOnly = false;
        if (el._plc) cursorToStart(el);
    }, false);
  
    function cursorToStart(input) {
        if (input.createTextRange) {
            var part = input.createTextRange();
            part.move("character", 0);
            part.select();
        } else if (input.setSelectionRange){
            input.setSelectionRange(0, 0);
        } input.focus();
    }
    function reverseStr(str) {
        if (!str) return "";
        return str.split("").reverse().join("");
    }
}
textarea {
    border: 1px solid gray;
    padding: 3px 6px;
    font-family: Arial;
    font-size: 13px;
    transition: .2s;
}
textarea:hover, textarea:focus {
    border-color: #2277cc;
}
textarea:focus {
    box-shadow: inset 0 0 5px #85B7E9;
}
*.unselectable {
    -webkit-user-select: none;
    -webkit-touch-callout: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    -o-user-select: none;
}
<textarea id="textarea"></textarea>

#1


51  

What you could do is add the text as value, which respects the line break \n.

您可以做的是将文本添加为value,它尊重断行\n。

$('textarea').attr('value', 'This is a line \nthis should be a new line');

Then you could remove it on focus and apply it back (if empty) on blur. Something like this

然后你可以在焦点上移除它,在blur中应用它(如果是空的)。像这样的东西

var placeholder = 'This is a line \nthis should be a new line';
$('textarea').attr('value', placeholder);

$('textarea').focus(function(){
    if($(this).val() === placeholder){
        $(this).attr('value', '');
    }
});

$('textarea').blur(function(){
    if($(this).val() ===''){
        $(this).attr('value', placeholder);
    }    
});

Example: http://jsfiddle.net/airandfingers/pdXRx/247/

例如:http://jsfiddle.net/airandfingers/pdXRx/247/

Not pure CSS and not clean but does the trick.

不是纯CSS,也不干净,但是很有用。

#2


137  

You can insert a new line html entity &#10; inside the placeholder attribute:

您可以插入一个新的行html实体 在占位符属性:

<textarea name="foo" placeholder="hello you&#10;Second line&#10;Third line"></textarea>

< span style = ' font - size: 9.0 pt; font - family:宋体;mso - ascii - font - family:

Works on: Chrome 62, IE10

用于:Chrome 62, IE10

Doesn't work on: Firefox 57, Safari 11

不支持:Firefox 57, Safari 11

https://jsfiddle.net/lu1s/bxkjLpag/2/

https://jsfiddle.net/lu1s/bxkjLpag/2/

#3


53  

Don't think you're allowed to do that: http://www.w3.org/TR/html5/forms.html#the-placeholder-attribute

不要认为你可以这样做:http://www.w3.org/TR/html5/forms.html#占位符属性

The relevant content (emphasis mine):

相关内容(重点是我的):

The placeholder attribute represents a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value. 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.

占位符属性表示一个短提示(一个单词或短短语),当控件没有值时,该提示用于帮助用户输入数据。提示可以是示例值,也可以是预期格式的简要描述。如果指定该属性,则必须具有不包含U+000A行提要(LF)或U+000D节返回(CR)字符的值。

#4


46  

UPDATE (Jan 2016): The nice little hack might not work on all browsers anymore so I have a new solution with a tiny bit of javascript below.

更新(2016年1月):这个漂亮的小技巧可能不再适用于所有浏览器,所以我有了一个新的解决方案,下面有一小段javascript代码。


A Nice Little Hack

It doesn't feel nice, but you can just put the new lines in the html. Like this:

感觉不太好,但是你可以把新的行放到html中。是这样的:

<textarea rows="6" id="myAddress" type="text" placeholder="My Awesome House,
        1 Long St
        London
        Postcode
        UK"></textarea>

Notice each line is on a new line (not being wrapped) and each 'tab' indent is 4 spaces. Granted it is not a very nice method, but it seems to work:

注意每一行都在一条新行上(没有被包装),每个“标签”缩进是4个空格。虽然这不是一个很好的方法,但它似乎是有效的:

http://jsfiddle.net/01taylop/HDfju/

http://jsfiddle.net/01taylop/HDfju/

  • It is likely that the indent level of each line will vary depending on the width of your text area.
  • 很可能每行的缩进级别会根据文本区域的宽度而变化。
  • It is important to have resize: none; in the css so that the size of the textarea is fixed (See jsfiddle).
  • 调整大小很重要:无;在css中,使textarea的大小是固定的(参见jsfiddle)。

Alternatively When you want a new line, hit return twice (So there is a empty line between your 'new lines'. This 'empty line' created needs to have enough tabs/spaces that would equate to the width of your textarea. It doesn't seem to matter if you have far too many, you just need enough. This is so dirty though and probably not browser compliant. I wish there was an easier way!

或者,当你想要一个新的行时,点击回车两次(所以在你的“新行”之间有一个空行。这个“空行”创建需要有足够的选项卡/空格,这将等同于textarea的宽度。如果你有太多的东西,你只需要足够的。这太脏了,而且可能不兼容浏览器。我希望有更简单的方法!


A Better Solution

Check out the JSFiddle.

查看JSFiddle。

  • This solution positions a div behind the textarea.
  • 这个解决方案在文本区域后面放置一个div。
  • Some javascript is used to change the background colour of the textarea, hiding or revealing the placeholder appropriately.
  • 一些javascript用于更改文本区域的背景颜色,适当地隐藏或显示占位符。
  • The inputs and placeholders must have the same font sizes, hence the two mixins.
  • 输入和占位符必须具有相同的字体大小,因此有两个mixin。
  • The box-sizing and display: block properties on the textarea are important or the div behind it will not be the same size.
  • 方框大小和显示:在textarea上的块属性很重要,或者它后面的div不会是相同的大小。
  • Setting resize: vertical and a min-height on the textarea are also important - notice how the placeholder text will wrap and expanding the textarea will keep the white background. However, commenting out the resize property will cause issues when expanding the textarea horizontally.
  • 设置大小:垂直的和最小的高度也很重要——注意占位符文本将如何包装和展开文本区域将保持白色背景。但是,在水平扩展文本区域时,注释出resize属性将导致问题。
  • Just make sure the min-height on the textarea is enough to cover your entire placeholder at its smallest width.**
  • 只需确保textarea上的最小高度足够覆盖整个占位符的最小宽度。**

在textarea的占位符属性中插入换行符?

HTML:

HTML:

<form>
  <input type='text' placeholder='First Name' />
  <input type='text' placeholder='Last Name' />
  <div class='textarea-placeholder'>
    <textarea></textarea>
    <div>
      First Line
      <br /> Second Line
      <br /> Third Line
    </div>
  </div>
</form>

SCSS:

SCSS:

$input-padding: 4px;

@mixin input-font() {
  font-family: 'HelveticaNeue-Light', 'Helvetica Neue Light', 'Helvetica Neue', Helvetica, Arial, 'Lucida Grande', sans-serif;
  font-size: 12px;
  font-weight: 300;
  line-height: 16px;
}

@mixin placeholder-style() {
  color: #999;
  @include input-font();
}

* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

form {
  width: 250px;
}

input,textarea {
  display: block;
  width: 100%;
  padding: $input-padding;
  border: 1px solid #ccc;
}

input {
  margin-bottom: 10px;
  background-color: #fff;

  @include input-font();
}

textarea {
  min-height: 80px;
  resize: vertical;
  background-color: transparent;
  &.data-edits {
    background-color: #fff;
  }
}

.textarea-placeholder {
  position: relative;
  > div {
    position: absolute;
    z-index: -1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    padding: $input-padding;
    background-color: #fff;
    @include placeholder-style();
  }
}

::-webkit-input-placeholder {
  @include placeholder-style();
}
:-moz-placeholder {
  @include placeholder-style();
}
::-moz-placeholder {
  @include placeholder-style();
}
:-ms-input-placeholder {
  @include placeholder-style();
}

Javascript:

Javascript:

$("textarea").on('change keyup paste', function() {
  var length = $(this).val().length;
  if (length > 0) {
    $(this).addClass('data-edits');
  } else {
    $(this).removeClass('data-edits');
  }
});

#5


14  

How about a CSS solution: http://cssdeck.com/labs/07fwgrso

CSS解决方案:http://cssdeck.com/labs/07fwgrso ?

::-webkit-input-placeholder::before {
  content: "FIRST\000ASECOND\000ATHIRD";
}

::-moz-placeholder::before {
  content: "FIRST\000ASECOND\000ATHIRD";
}

:-ms-input-placeholder::before {
  content: "FIRST\000ASECOND\000ATHIRD";
}

#6


11  

Salaamun Alekum

Salaamun Alekum

&#10;

Works For Google Chrome

适用于谷歌浏览器

在textarea的占位符属性中插入换行符?

<textarea placeholder="Enter Choice#1 &#10;Enter Choice#2 &#10;Enter Choice#3"></textarea>

I Tested This On Windows 10.0 (Build 10240) And Google Chrome Version 47.0.2526.80 m

我在Windows 10.0 (Build 10240)和谷歌Chrome版本47.0.2526.80 m上进行了测试

08:43:08 AST 6 Rabi Al-Awwal, 1437 Thursday, 17 December 2015

2015年12月17日,星期四,东部时间8点43分08分

Thank You

谢谢你!

#7


7  

Nope you cant do that in the placeholder attribute. You cant even html encode newlines like &#13;&#10; in a placeholder.

不,在占位符属性中不能这样做。甚至连html都不能编码像#13;#10这样的换行在一个占位符。

A small demo:

一个小演示:

http://jsfiddle.net/pdXRx/5/

http://jsfiddle.net/pdXRx/5/

#8


5  

You can't do it with pure HTML, but this jQuery plugin will let you: https://github.com/bradjasper/jQuery-Placeholder-Newlines

你不能用纯HTML来做,但是这个jQuery插件会让你:https://github.com/bradjasper/jQuery-Placeholder-Newlines

#9


5  

Try this:

试试这个:

<textarea
placeholder="Line1&#x0a;&#x09;&#x09;&#x09;Line2"
cols="10"
rows="5"
style="resize:none">
</textarea>

http://jsfiddle.net/vr79B/

http://jsfiddle.net/vr79B/

#10


4  

A slightly improved version of the Jason Gennaro's answer (see code comments):

杰森·杰纳罗的回答稍有改进(参见代码注释):

var placeholder = 'This is a line \nthis should be a new line';
$('textarea').attr('value', placeholder);
$('textarea').focus(function(){
    if($(this).val() == placeholder){
        // reset the value only if it equals the initial one    
        $(this).attr('value', '');
    }
});
$('textarea').blur(function(){
    if($(this).val() == ''){
        $(this).attr('value', placeholder);
    }    
});
// remove the focus, if it is on by default
$('textarea').blur();

#11


4  

I liked the work of Jason Gennaro and Denis Golomazov, but I wanted something that would be more globally useful. I have modified the concept so that it can be added to any page without repercussion.

我喜欢杰森·杰纳罗(Jason Gennaro)和丹尼斯·戈罗马佐夫(Denis Golomazov)的作品,但我想要的是更具有全球意义的作品。我已经修改了这个概念,这样它就可以添加到任何页面而不产生任何影响。

http://jsfiddle.net/pdXRx/297/

http://jsfiddle.net/pdXRx/297/

<h1>Demo: 5 different textarea placeholder behaviors from a single JS</h1>

<h2>Modified behaviors</h2>

<!-- To get simulated placeholder with New Lines behavior,
     add the placeholdernl attribute -->

<textarea placeholdernl>    (click me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<textarea placeholder='Address' placeholdernl>    (click me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<h2>Standard behaviors</h2>

<textarea placeholder='Address'>    (delete me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<textarea>    (delete me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<textarea placeholder='Address'></textarea>

The javascript is very simple

javascript非常简单

<script>
(function($){
var handleFocus = function(){
    var $this = $(this);
    if($this.val() === $this.attr('placeholdernl')){
        $this.attr('value', '');
        $this.css('color', '');
    }
};

var handleBlur = function(){
    var $this = $(this);
    if($this.val() == ''){
        $this.attr('value', $this.attr('placeholdernl'))
        $this.css('color', 'gray');
    }    
};

$('textarea[placeholdernl]').each(function(){
    var $this = $(this),
        value = $this.attr('value'),
        placeholder = $this.attr('placeholder');
    $this.attr('placeholdernl', value ? value : placeholder);
    $this.attr('value', '');
    $this.focus(handleFocus).blur(handleBlur).trigger('blur');
});
})(jQuery);
</script>

#12


4  

Use &#10; in place of /n this will change the line.

使用& # 10;代替/n,这将改变直线。

#13


2  

I modified @Richard Bronosky's fiddle like this.

我修改了@Richard Bronosky的小提琴。

It's better approach to use data-* attribute rather than a custom attribute. I replaced <textarea placeholdernl> to <textarea data-placeholder> and some other styles as well.

使用data-*属性比使用自定义属性更好。我将

edited
Here is the Richard's original answer which contains full code snippet.

这里编辑的是Richard的原始答案,其中包含完整的代码片段。

#14


2  

HTML

<textarea data-placeholder="1111\n2222"></textarea>

JS

$('textarea[data-placeholder]').each(function(){
    var $this = $(this),
        placeholder = $this.data('placeholder'),
        placeholderSplit = placeholder.split('\\n');
    placeholder = placeholderSplit.join('\n');
    $this.focus(function(){
        var $this = $(this);
        if($this.val() === placeholder){
            $this.val('');
            // $this.removeClass('placeholder');
        }
    }).blur(function(){
        var $this = $(this);
        if($this.val() == '') {
            $this.val(placeholder);
            // $this.addClass('placeholder');
        }
    }).trigger('blur');
});

#15


1  

very simple

非常简单的

  var position = your break position;
    var breakLine = "&#13;&#10;";//in html 
    var output = [value.slice(0, position), breakLine, value.slice(position)].join('');
    return output;

value represent the original string

值表示原始字符串

#16


1  

Check out this solution with custom placeholder.

使用自定义占位符检查此解决方案。

  • You get multiline placeholder that works in all browsers (including Firefox)
  • 在所有浏览器(包括Firefox)中都可以使用多行占位符
  • It is posible to customise placeholder as you want
  • 可以根据需要定制占位符

Demo on fiddle.

在小提琴的演示。

$(document).on('input', '#textArea', function () {
	
        if ($('#textArea').val()) {
            $('#placeholderDiv').hide();
        } else {
            $('#placeholderDiv').show();
        }   
});
#textAreaWrap {
    position: relative;
    background-color: white;
}

#textArea {
    position: relative;
    z-index: 1;
    width: 350px;
    height: 100px;
    min-height: 100px;
    padding: 6px 12px;
    resize: vertical;
    background-color: transparent;
    /* When set background-color: transparent - Firefox  displays
    unpleasant textarea border. Set border style to fix it.*/
    border: 1px solid #a5a5a5;
}

#placeholderDiv {
    position: absolute;
    top: 0;
    padding: 6px 13px;
    color: #a5a5a5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="textAreaWrap">
    
<textarea id="textArea"></textarea>

<!-- Check here. If textarea has content -
     set for this div attribute style="display: none;" -->
<div id="placeholderDiv">Multiline textarea<br>
                         placeholder<br>
                         <br>
                         that works in Firefox</div>
    
</div>

#17


0  

I don't like hiding the placeholder when you focus the textarea. So I made a constructor function Placeholder that looks exactly like the built-in placeholder and works also in other browsers than Google Chrome. It's very convenient because you can use the Placeholder function as often as you want and it doesn't even need jQuery.

我不喜欢隐藏占位符当你聚焦文本区域。因此,我创建了一个构造函数占位符,它看起来完全像内置的占位符,在其他浏览器中也比谷歌Chrome更有效。它非常方便,因为您可以随时使用占位符函数,甚至不需要jQuery。

EDIT:

编辑:

It now also handles special cases, like inserting the placeholder, correctly.

它现在还可以正确地处理特殊情况,如插入占位符。

var textarea = document.getElementById("textarea");
new Placeholder(textarea, "Line 1\nLine 2\nLine 3");

function Placeholder(el, placeholder) {
    if (el.value == "" || el.value == placeholder) {
        el.style.color = "gray";
        el.value = placeholder;
        el._plc = true;
        el.className += " unselectable";
    }
    function keyPress(e) {
        window.setTimeout(function() {
            var replaced = reverseStr(el.value).replace(reverseStr(placeholder), "");
            
            if (el.value == "") {
                el.value = placeholder;
                el.style.color = "gray";
                cursorToStart(el);
                el._plc = true;
                el.className += " unselectable";
            } else if (el._plc && el.value.endsWith(placeholder) && replaced !== "") {
                el.value = reverseStr(replaced);
                el.style.color = "black";
                el._plc = false;
                el.readOnly = false;
                el.className = el.className.replace("unselectable", "");
            } else if (el._plc && el.readOnly) {
                var ch = String.fromCharCode(e.charCode);
                if (e.keyCode == 13) ch = "\n";     // ENTER
                else if (e.charCode == 0) return;   // non-character keys
                
                el.value = ch;
                el.style.color = "black";
                el._plc = false;
                el.readOnly = false;
                el.className = el.className.replace("unselectable", "");
            }
        }, 10);
    }
    el.addEventListener("keypress", keyPress, false);
    el.addEventListener("paste", keyPress, false);
    el.addEventListener("cut", keyPress, false);
    el.addEventListener("mousedown", function() {
        if (el._plc) el.readOnly = true;
    }, false);
    el.addEventListener("mouseup", function() {
        el.readOnly = false;
        if (el._plc) cursorToStart(el);
    }, false);
  
    function cursorToStart(input) {
        if (input.createTextRange) {
            var part = input.createTextRange();
            part.move("character", 0);
            part.select();
        } else if (input.setSelectionRange){
            input.setSelectionRange(0, 0);
        } input.focus();
    }
    function reverseStr(str) {
        if (!str) return "";
        return str.split("").reverse().join("");
    }
}
textarea {
    border: 1px solid gray;
    padding: 3px 6px;
    font-family: Arial;
    font-size: 13px;
    transition: .2s;
}
textarea:hover, textarea:focus {
    border-color: #2277cc;
}
textarea:focus {
    box-shadow: inset 0 0 5px #85B7E9;
}
*.unselectable {
    -webkit-user-select: none;
    -webkit-touch-callout: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    -o-user-select: none;
}
<textarea id="textarea"></textarea>