其他人问过这个问题,但答案都是针对jQuery的。
答案 0 :(得分:5)
首先,你应该使用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') });
});
});
答案 1 :(得分:-2)
/**
* 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;
}
}
});
}