1

我试图在我的网站中获得我认为非常好的 HTML5 ——input字段的占位符属性。

但是我在我的网站上获得它的方式严重退化。因为我跳过了字段的标签并使用占位符作为其标签。

目前我有几个带占位符的输入字段,它们看起来像这样:

<input placeholder="hereismyplaceholder" />

但是在 HTML5 占位符支持不可用的情况下,我希望所有带有占位符的输入字段都更改为此。显然与它们等效的占位符文本:

<input onblur="if (this.value == '') {this.value = 'hereismyplaceholder';}" onfocus="if (this.value == 'hereismyplaceholder') {this.value = '';}" value="hereismyplaceholder" />

因此,我引入了Modernizr,并使用以下 javascript 来检测占位符:

if (Modernizr.input.placeholder) {
} else {
// BUT I NEED SOMETHING IN HERE
}

但我不知道现在该怎么办。因为我没有使用 javascript 的经验,所以我不是开发人员。

请最简单的解决方案是最好的。我对好的做法并不在意,我只是希望它现在可以工作。

4

2 回答 2

0

这里有一个例子,http://www.modernizr.com/docs/#input

对于您的特定用例,代码应该是

// if placeholder isn't supported:
if (!Modernizr.input.placeholder){
  // use a input hint script
  setInputHint(document.getElementById('idoftheinputelement'),'hereismyplaceholder');
}
于 2011-05-16T18:41:20.093 回答
0

您没有要求使用 jQuery,但我不想担心跨浏览器问题:

if (!Modernizr.input.placeholder) {
  $("input[type=text]")
  .focus(function(e){
      if (this.value == $(this).attr('placeholder')) {
         this.value = '';
      }         
  })
  .blur(function(e){
    setPlaceholder(this);
  }).each(function(index, el){
    setPlaceholder(el);
  });

  function setPlaceholder(el) {
    if (el.value  == '') {
        el.value = $(el).attr('placeholder');
    }
  }
}
于 2011-05-16T18:44:33.870 回答