如何使用 Mootools 支持 IE 8-9 中的“占位符”属性?

Posted

技术标签:

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

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

【问题讨论】:

mootools.net/forge/browse?search=placeholder 和 google.com/search?hl=en-GB&hl=en&q=mootools+placeholder - 有很多选择。如果你想要 mootools 的答案,那就去找那个? 为什么这个问题被否决了?这是一个非常好的问题! 【参考方案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 来做你想做的事情。

以上是关于如何使用 Mootools 支持 IE 8-9 中的“占位符”属性?的主要内容,如果未能解决你的问题,请参考以下文章

一段Css代码不支持IE11疑问,但支持IE7,8,9,10和谷歌!唯独不支持IE11!

JavaScript Aeron Glemamn Calendar.js修复了IE9对Mootools 1.2.4

iecors - IE 8 + 9 中用于 CORS 的 jQuery 插件在页面首次加载时不起作用

如何实现背景透明,文字不透明,兼容所有浏览器?

请问怎么让IE支持ES6的语法?

IE6,7,8,9还有火狐浏览器的兼容