【问题标题】:How can I support the 'placeholder' attribute in IE 8-9 with Mootools?如何使用 Mootools 支持 IE 8-9 中的“占位符”属性?
【发布时间】:2012-06-05 04:58:10
【问题描述】:

其他人也问过这个,但答案都是jQuery的。

【问题讨论】:

标签: javascript html internet-explorer mootools placeholder


【解决方案1】:
/**
 * IE doesn't support the placeholder attribute, but we can set the value attribute.
 */
if (Browser.Engines.trident()) {
  var elements = $$('input[placeholder]');
  elements.map(function(it) {
    if (!it.getAttribute('value')) {
      it.setAttribute('value', it.getAttribute('placeholder'));
      it.onfocus = function() {
        it.setAttribute('value', '');
        it.onfocus = null;
      }
    }
  });
}

【讨论】:

  • 这很平淡,在太多情况下会失败,从 mootools 的角度来看,它也写得不是很好。
  • 首先,这似乎是针对旧版本的 Mootools。其次,Browser.Engines.trident() 从来就不是什么。我认为您的意思是Browser.Engine.trident,但这仍然是一种糟糕的测试方式。您需要测试功能,而不是浏览器。
【解决方案2】:

首先,您应该使用 Mootools 插件“OverText”http://mootools.net/docs/more/Forms/OverText,它基本上模拟了此功能。它实际上可以在任何浏览器中工作,因此,如果您愿意,您可以使用它并完全忘记占位符属性。但是,如果您想在可用时支持占位符但在旧版浏览器中使用 OverText,您可以这样做:

window.addEvent('domready', function() {
    // create a test element
    var test = new Element('input'); 
    // if it has 'placeholder' this browser supports it already so you can exit
    if(("placeholder" in test)) { return; } 
    // for older browsers, get all the inputs which you have assigned a 'placeholder' attribute to
    $$('input[placeholder]').each(function(el) { 
        // and create an overtext for them using the value of the placeholder attribute
        new OverText(el, { textOverride: el.get('placeholder') });
    });
});

【讨论】:

  • 您应该始终使用本机功能并包含 JS 或其他备份,您的网站会运行得更快,总体上具有更好的可用性
  • 为什么会被否决?这是在可用时使用本机功能,并在旧浏览器上使用 JS。这就是这样做的方法。
  • 哈!另一个反对票?这是BS。我向你保证,这是 THE WAY 来做你想做的事情。
猜你喜欢
  • 2013-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-16
  • 2013-11-25
  • 2014-07-13
  • 2011-12-21
  • 2012-10-17
相关资源
最近更新 更多