在文本区域的占位符属性内插入换行符?

我尝试了一些方法,但没有一个奏效。有人知道绕过这个的妙招吗?

<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。它只是textarea的宽度。

看到的: http://jsfiddle.net/pdXRx/

201941 次浏览

不要认为你可以这样做:http://www.w3.org/TR/html5/forms.html#the-placeholder-attribute

相关内容(重点我):

占位符属性表示提示(一个单词或简短的提示) 短语),用于帮助用户在控件出现故障时输入数据 没有价值。方法的示例值或简要描述可以是提示 预期的格式。如果指定了属性,则该属性的值必须为 不包含U+000A换行(LF)或U+000D回车(CR) 字符。< /强> < / p >

旧的回答:

不,你不能在占位符属性中这样做。你甚至不能在占位符中编码像&#13;&#10;这样的换行符。

新回答:

现代浏览器为您提供了几种方法。请看这个JSFiddle:

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

你可以做的是将文本添加为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,也不是清洁,但它做到了。

你不能用纯HTML做到这一点,但这个jQuery插件将让你:https://github.com/bradjasper/jQuery-Placeholder-Newlines

更新(2016年1月):这个漂亮的小黑客可能不再适用于所有的浏览器,所以我有一个新的解决方案,下面有一小部分javascript。


一个不错的小技巧

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

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

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

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

  • 每行的缩进程度可能会根据文本区域的宽度而变化。
  • 在css中有resize: none;是很重要的,这样文本区域的大小是固定的(参见jsfiddle)。

< >强或者 当你想要一个新的行,点击返回两次(所以在你的“新行”之间有一个空行。这个“空行”创建需要有足够的制表符/空格,将等同于你的文本区域的宽度。如果你有太多似乎并不重要,你只需要足够。这太脏了,可能不兼容浏览器。我希望有更简单的方法!< / p >


更好的解决方案

检查JSFiddle

  • 这个解决方案在文本区域后面放置了一个div。
  • 一些javascript被用来改变文本区域的背景颜色,适当地隐藏或显示占位符。
  • 输入和占位符必须具有相同的字体大小,因此有两个mixin。
  • textarea中的box-sizingdisplay: block属性很重要,否则后面的div将不会是相同的大小。
  • 在文本区域上设置resize: verticalmin-height也很重要——注意占位符文本将如何自动换行,展开文本区域将保持白色背景。然而,注释掉resize属性会在水平展开文本区域时引起问题。
  • 只要确保文本区域的最小高度足以覆盖整个占位符的最小宽度

JSFiddle截图

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:

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

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

稍微改进了Jason Gennaro的回答(见代码注释):

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();

我喜欢Jason Gennaro和Denis Golomazov的作品,但我想要一些在全球范围内更有用的东西。我已经修改了这个概念,这样它就可以添加到任何页面而不受影响。

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>

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>

如何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";
}

试试这个:

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

http://jsfiddle.net/vr79B/

我修改了@Richard Bronosky的小提琴像这样

使用data-*属性而不是自定义属性是更好的方法。 我将<textarea placeholdernl>替换为<textarea data-placeholder>和其他一些样式 < p > 编辑 < br > 下面是Richard的原来的答案,包含完整的代码片段

你可以在占位符属性中插入一个新的行html实体&#10;:

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

Works on: Chrome 62, IE10, Firefox 60

Doesn't work on: Safari 11

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

非常简单的

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

值表示原始字符串

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

  • 您将获得在所有浏览器(包括Firefox)中都可用的多行占位符
  • 这是可以自定义占位符,因为你想要

小提琴演示

.
$(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>

Salaamun Alekum

&#10;

适用于谷歌Chrome浏览器

enter image description here

<textarea placeholder="Enter Choice#1 &#10;Enter Choice#2 &#10;Enter Choice#3"></textarea>
我在Windows 10.0 (Build 10240)和谷歌Chrome版本上测试了这个 47.0.2526.80 m < / p >

2015年12月17日星期四,1437,拉比奥瓦尔,AST 6 08:43:08

谢谢你!

我不喜欢隐藏占位符当你聚焦文本区域。所以我做了一个构造函数Placeholder,看起来完全像内置占位符,也工作在其他浏览器,而不是谷歌Chrome。它非常方便,因为你可以随时使用Placeholder函数,甚至不需要jQuery。

编辑:

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

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

超文本标记语言

<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');
});

使用&#10;代替\n,这将改变行。

Textarea尊重占位符的空白属性。https://www.w3schools.com/cssref/pr_text_white-space.asp

将它设置为预行,为我解决了这个问题。

textarea {
white-space: pre-line;
}
<textarea placeholder='This is a line
should this be a new line'></textarea>

只添加 作为断行,不需要写任何CSS或javascript。

textarea{
width:300px;
height:100px;


}
<textarea placeholder='This is a line this &#10should be a new line'></textarea>


<textarea placeholder=' This is a line


should this be a new line?'></textarea>

这个问题可以通过使用占位符显示的选择器和超级强加的背景来解决,如果你的实现允许:

textarea:not(:placeholder-shown) {
background: #fff;
}


div {
top: 0;
left: 14px;
color: rgba(0,0,0,0.4);
z-index: -1;
position: absolute;
line-height: 1.2;
white-space: pre-wrap;
}

< a href = " https://codepen。io/franciscoaquino/pen/YzyBPYK" rel="nofollow noreferrer">https://codepen.io/franciscoaquino/pen/YzyBPYK

选择器支持:

https://caniuse.com/#feat=css-placeholder-shown

根据我所看到的三种不同技巧的组合,这似乎在我测试过的所有浏览器中都有效。

HTML:

<textarea placeholder="Line One&#10;Line Two&#10;&#10;Line Four"></textarea>

JS在HTML文件底部:

<script>
    

var textAreas = document.getElementsByTagName('textarea');


Array.prototype.forEach.call(textAreas, function(elem) {
elem.placeholder = elem.placeholder.replace(/\u000A/g,
'                                                     \
\
\
\n\u2063');
});


</script>

注意,额外的空间将导致一个干净的环绕,但必须有足够的空间,它将填补文本区域的宽度,我放置了足够的空间,它足以为我的项目,但你可以通过观察文本区域来生成它们。宽度和计算适当的基数。

如果你在ASP中使用Razor。NET项目,你可以做下面的事情,这对很长的占位符值很有帮助:

@{
string strPlaceholder = "Shipment Id to Update, Container Id to Update, New Tracking Number \r\n"
+ "Shipment Id to Update, Container Id to Update, New Tracking Number \r\n"
+ "Shipment Id to Update, Container Id to Update, New Tracking Number \r\n"
+ "\r\n"
+ "i.e. to update all containers with shipment Id 5803407, etner like this: \r\n"
+ "5803407, , 1Z20579A0322337062 \r\n"
+ "\r\n"
+ "or to update a specific container Id, enter like this: \r\n"
+ "5803407, 112546247, 1Z20579A0322337062 \r\n"
;
}
<textarea type="text" class="form-control" style="height:650px;" id="ShipmentList" name="ShipmentList"
placeholder="@strPlaceholder" required></textarea>

enter image description here

我来这里是为了一个多行占位符解决方案,然后我意识到接受的解决方案不工作时,文本区域是在formik形式。

在这种情况下,解决方案就是模板字面量。它允许您指定多行文本字符串。

    <textarea
cols={40}
placeholder={`day 1: Temple visit,&#13;&#10;
day 2: Jungle barbeque,\n
day 3: Waterfall visit in the evening,\n
day 4: Visit UNESCO World Heritage Site,\n
day 5: Art gallery show,\n
day 6: Visit grand swimming pool,\n
day 7: Visit to Blue fort`}
rows={20}
/>

source

在php工作良好反斜杠+ r (r \):

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

需要注意的是,问题的前提是与W3规格不符,因此不能保证行为,当<textarea>在HTML中定义时,使用&x10;的解决方案是有效的:

<textarea
placeholder="HTML entity works &#10; but unicode entity hard-coded \u000A !">
</textarea>

enter image description here

但是如果<textarea>是用JavaScript创建的,那么&#10;实体将在输出中硬编码。然而,使用unicode等效的\u000A是可以的:

let myArea = document.createElement("textarea");
myArea.placeholder = "Unicode works \u000A But HTML entity hard-coded &#10; !";

enter image description here