繁体   English   中英

如何在用户在 html textarea 中输入文本之前添加永久文本?

[英]How do I add permanent text before user enters a text in html textarea?

我想在用户输入类似 cmd 的文本之前在 html textarea 中添加一个永久文本,其中在编写任何代码之前写入路径。 我怎样才能做到这一点?

好吧,据我所知,没有您想要的内置功能。

但是,结合一些事情,我们可以实现接近它的目标。

诀窍是:

  • 将 textarea 包裹在div标签中
  • 在给定的div上使用::before伪元素来添加和定位固定文本
  • 在 textarea 上使用text-indent css 属性为我们的固定文本腾出空间:)

 #cont { position: relative; display: block; } #cont::before { content: 'myFixedText:\\>'; position: absolute; top: 6px; left: 6px; z-index: 99; font-size: 14px; font-family: Arial, Helvetica, sans-serif; font-weight: bold; } textarea { text-indent: 100px; min-width: 300px; min-height: 150px; font-size: 14px; padding: 5px; font-family: Arial, Helvetica, sans-serif }
 <div id="cont"> <textarea></textarea> </div>

你可以用 JavaScript 来实现:

 $('textarea.text').each(function() { var prefix = $('<span/>') .text($(this).data('prefix')) .addClass('prefix') .appendTo('body') .css({ left: $(this).position().left + 'px', top: $(this).position().top + 'px', }); $(this).css({ textIndent: prefix.outerWidth() + 'px' }); });
 textarea, span.prefix { font-size: 1em; font-weight: normal; padding: 2px; border-width: 1px; } span.prefix { position: absolute; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea class="text" data-prefix="Your path or text > "></textarea>

要在 textarea 中获取文本,您可以执行以下操作:

<textarea>Insert permanent text here</textarea>

占位符文本将允许用户在它上面输入,这不是永久性的。

像这样使用占位符属性:

<textarea placeholder="Describe yourself here..."></textarea>

这是一个在 input 或 textarea 中输入任何内容之前输入文本的示例:

<input type="text" name="TheName" **placeholder=**"Type your name">
<textarea name="TheTextArea" **placeholder=**"Your textarea..."></textarea>

Placeholder Attribute 是 input 和 textarea 最常用的选项。 但是 value 也可以用于那里的实际文本。 <textarea value="Something here" placeholder="Something here">Something here</textarea>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM