【问题标题】:Keep initial value in textbox after click单击后在文本框中保留初始值
【发布时间】:2015-11-27 16:38:06
【问题描述】:

点击后我需要在我的文本框中保留一个初始值/占位符。它需要是只读的,但允许用户在预设文本之后添加字符:

<input type="text" placeholder="I will " name="title" required maxlength="50">

当用户点击文本框时,我需要将光标移动到“我愿意”一词之后并允许他们输入。他们无法删除“我愿意”的字眼。

【问题讨论】:

  • 你让这变得比它应该的更复杂,只需这样做:&lt;label&gt;I will &lt;input type="text" name="title" required maxlenght="50" /&gt;&lt;/label&gt; 并使用 css 设置样式,使其看起来像同一个文本框。
  • 还有一些想法here

标签: javascript jquery html


【解决方案1】:

根据 @Josep 建议检查这个基本示例:

label{
    border: 1px solid;
}
input{
    border: 0px;
    height: 100%;
    font-family: inherit;
    outline: none;
    font-size: 16px;
    padding: 0px;
}
&lt;label&gt;I will &lt;input type="text" name="title" required maxlenght="50" /&gt;&lt;/label&gt;

Outline: none 将删除主流浏览器中输入框周围的蓝色框。 (只是一种美学改进)

【讨论】:

    【解决方案2】:

    尝试使用focusout 事件在click 事件之后重置valuereadonly 属性

    $("input").on({
      click:function(e) {
        $(this).removeAttr("readOnly")
      }, 
      focusout: function(e) {    
        this.value = this.getAttribute("placeholder") 
                     + this.value.replace(/^I will /, "");
        $(this).prop("readOnly", true);
      }
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
    </script>
    <input type="text" placeholder="I will " name="title" required maxlength="50" readonly>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 2018-08-17
      • 2014-03-14
      • 1970-01-01
      相关资源
      最近更新 更多