Adding HTML Within Placeholder

左心房为你撑大大i 提交于 2021-01-28 11:12:34

问题


I am a fan of using HTML placeholders, as it helps describe to the user what sort of content they need to input. However, sometimes you need to give the user more information than just a simple sentence. Basically I'd like to be able to add line breaks, tabs, etc. into my textarea placeholder. I've heard of using special coding to do this (And have written pieces of code using these), but I find it rather unreliable. For example, certain browsers will display different amounts of white space for the codes. An example of this code would be like the following:

<textarea name="parts" id="parts" placeholder="Some-Part&#x0a;&#x09;&#x09;&#x09;&#x0a;&#x09;&#x09;&#x09;&#x09;&#x0a;&#x09;&#x09;&#x09;&#x09;&#x0a;..."></textarea>

Thus, my thought at a solution would be to have the ability to put actual HTML elements into the placeholder. I have been researching on how I might accomplish this, but have been unable to find anything on it. Do you have any idea where I might go to find functionality similar or the same as this? Or, do you have an alternative of what I might be able to do to accomplish the same thing?


回答1:


The placeholder attribute has plain text as its value, by definition. No tags are recognized. Character references are recognized, but the effects of characters like TAB U+0009 (&#09;) are defined to be implementation-dependent.

So no, you can’t have HTML markup there. Your ultimate problem might have a solution, but you have not described that problem. As a rule, if you need placeholder value that is not a short plain text string, you are trying to use the attribute against its definition. It is meant to be a hint that augments the field label and description, instead of replacing them. Normally, any descriptions that are needed should precede the field, and there you can use HTML markup as desired.




回答2:


HTML is not allowed inside a textarea tag. I'd recommend a different UI/implementation, but you could do something like this:

<div contenteditable="true" class="myarea">
    <em>Placeholder</em>
</div>

And then mimic a text area with a css class. Then you could clear the contents on focus

var firstFocus = true;
$('#myarea').focus(function() {
    if (firstFocus) {
        $('#myarea').html('');
        firstFocus = false;
    }
});

As you can see, it starts getting pretty ugly. This won't behave exactly the same way as the placeholder attribute either, so you'd have to manage text cursors and change events, etc. Generally I feel placeholder text is a rather poor UI since the info disappears as soon as you start typing :p




回答3:


I was able to find this answer which uses js to insert line breaks. Insert line break inside placeholder attribute of a textarea?



来源:https://stackoverflow.com/questions/27133427/adding-html-within-placeholder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!