【问题标题】:Is it possible to change input value using CSS?是否可以使用 CSS 更改输入值?
【发布时间】:2013-03-04 22:26:20
【问题描述】:

我可以在用户点击时使用 CSS 更改输入字段的值吗?

喜欢:

<input type=text name=username>
<input type=password name=password>

因此,当用户点击该字段时,文本将消失,他将能够写一些东西。

我试过了:

input[value="Input desired username here"] {
styles...
}

有什么线索吗?

【问题讨论】:

标签: css forms input


【解决方案1】:

没有必要为此使用 css。你可以为你的输入标签使用占位符属性,它会在输入框中显示一个默认值:

<input type="text" name="username" placeholder="Username" />

请注意placeholder 属性并非在所有浏览器中都受支持,如果您想让它跨浏览器,您可以编写一个 javascript 代码在您的输入框中放置一个默认值,或者使用这个简单而快速的修复方法:

<input type="text" name="username" onFocus="if(this.value=='Username') this.value='';" onBlur="if(this.value=='') this.value='Username';" value="Username" />

【讨论】:

  • 呃哈哈!!你很酷!非常感谢!
  • 搜索互联网 = 浪费几个小时 / 在 stackoverflow 上发布问题 = 浪费几分钟 / 得到准确答案 = 无价! :)
  • 不兼容?该死的,好得不像真的。实际上我正在考虑使用 CSS url(img)...
  • 好像只有
  • 我提供了另一种解决方案。大多数浏览器版本都支持第二个。
【解决方案2】:

这称为占位符。现代浏览器将允许您使用这样的占位符属性:

<input type="text" name="username" placeholder="Input desired username here" />

它会如你所愿。然后,您将需要利用 Modernizr 将该功能反向移植到旧版浏览器。像这样的 JavaScript 会有所帮助:

$(document).ready(function () {
  if(!Modernizr.input.placeholder) {
    $('[placeholder]').focus(function () {
      var input = $(this);
      if (input.val() == input.attr('placeholder')) {
        input.val('');
        input.removeClass('placeholder');
      }
    }).blur(function () {
      var input = $(this);
      if (input.val() == '' || input.val() == input.attr('placeholder')) {
        input.addClass('placeholder');
        input.val(input.attr('placeholder'));
    }).blur();
    $('[placeholder]').parents('form').submit(function () {
      $(this).find('[placeholder]').each(function () {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
          input.val('');
        }
      })
    });
  }
})

【讨论】:

    猜你喜欢
    • 2020-01-05
    • 2021-06-30
    • 1970-01-01
    • 2013-07-16
    • 2011-01-22
    • 2019-10-09
    • 1970-01-01
    • 2013-04-21
    相关资源
    最近更新 更多