温馨提示:本文翻译自stackoverflow.com,查看原文请点击:html - Insert line break inside placeholder attribute of a textarea?
html

html - 在textarea的占位符属性内插入换行符?

发布于 2020-03-30 21:32:10

我尝试了几种方法,但是都没有用。有谁知道解决这个问题的妙招?

<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 -->

更新:在chrome中不起作用。只是文本区域的宽度。

请参阅: http //jsfiddle.net/pdXRx/

查看更多

提问者
amosrivera
被浏览
12
1,193 2013-09-27 03:26

您可以做的是将文本添加为value,这要注意换行符\n

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

然后,您可以将其移除,focus然后将其重新应用(如果为空)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);
    }    
});

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

不是纯CSS也不干净,但是可以解决问题。