【问题标题】:How to add placeholder while focusout for all the fields in form?如何在表单中的所有字段聚焦时添加占位符?
【发布时间】:2019-10-09 01:14:26
【问题描述】:
$('*').focus(function(){
$(this).removeAttr("placeholder");
});

这用于我表单中的所有字段。但我找不到如何添加。

$('*').focusout(function(){
$(this).attr("placeholder","abc"); 
} 

这用于单个字段,但我需要所有字段,例如隐藏和显示

【问题讨论】:

  • 你可以使用 each() 函数。阅读docs
  • 你想达到什么目的?为什么你首先要删除该属性?你这样做是不是因为它比使用所有几种特定于供应商的 CSS 方式更直接?

标签: jquery html css textinput


【解决方案1】:

不是很优化,但可以工作

$('*:input').each(function(){
$(this).data('placeholder',$(this).attr("placeholder"))
$(this).removeAttr("placeholder");
$(this).on('focus', function(){
	$(this).attr("placeholder", $(this).data('placeholder'));
});
$(this).on('focusout', function(){
	$(this).removeAttr("placeholder");
});
});

【讨论】:

  • 感谢您的回答。但我的表单包含所有类型的字段,如输入、选择、文本区域。每个字段都有不同的占位符。
  • 嗯好的我改了,:input 与 textareas 兼容,但选择没有占位符
【解决方案2】:

看看这个JSFiddle 示例,当您focusout 任何字段 时,所有输入的占位符 都会发生变化。

<form id="form">
  <p>Form</p>
  <p><input/></p>
  <p>
    <select>
      <option id="selectPlaceholder"></option>
      <option>Option 1</option>
      <option>Option 2</option>
      <option>Option 3</option>
    </select>
  </p>
  <p><textarea></textarea></p>
  <p>
    <button id="reset" type="button">Reset placeholder</button>
  </p>
</form>

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#form {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  margin: 0 auto;
  width: 300px;
}

input, select, textarea {
  width: 90%;
  text-align: center;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

$("input, select, textarea").focusout(function(){

    $("input, select, textarea").attr(
        'placeholder',
        'Text for the placeholder focusout'
    )
    $("#selectPlaceholder").html('Text for the placeholder focusout');

});

$('#reset').click(function(){
    $('input, select, textarea').removeAttr('placeholder');
    $('#selectPlaceholder').html('');
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 2017-10-23
    • 2012-11-11
    • 2012-08-02
    • 2015-07-01
    • 2016-10-04
    相关资源
    最近更新 更多