属性占位符
HTML5 has introduced many features to the browser; some HTML-based, some in the form of JavaScript APIs, but all of them useful. One of my favorites if the introduction of the placeholder
attribute to INPUT elements. The placeholder
attribute shows text in a field until the field is focused upon, then hides the text. You've seen this technique a billion times with JavaScript, but native HTML5 support is even better!
HTML5为浏览器引入了许多功能。 有些基于HTML,有些采用JavaScript API的形式,但它们都非常有用。 如果将placeholder
属性引入INPUT元素,则是我的最爱之一。 placeholder
属性在字段中显示文本,直到该字段被关注,然后隐藏该文本。 您已经使用JavaScript看到了十亿次这种技术,但是原生HTML5支持甚至更好!
HTML (The HTML)
You'll notice that all you need to do is add a placeholder
attribute with the generic text of your choice. Nice that you don't need JavaScript to create this effect, huh?
您会注意到,您需要做的就是添加一个placeholder
属性以及您选择的通用文本。 很好,您不需要JavaScript即可创建这种效果,是吗?
检查占位符支持 (Checking for Placeholder Support)
Since placeholder
is a new capability, it's important to check for support in the user's browser:
由于placeholder
是一项新功能,因此检查用户浏览器中的支持很重要:
function hasPlaceholderSupport() { var input = document.createElement('input'); return ('placeholder' in input);}
If the user's browser doesn't support the placeholder
feature, you will need to employ a fallback with MooTools, Dojo, or the JavaScript toolkit of your choice:
如果用户的浏览器不支持placeholder
功能,则需要使用MooTools,Dojo或您选择JavaScript工具包进行后备管理:
/* mootools ftw! */var firstNameBox = $('first_name'), message = firstNameBox.get('placeholder');firstNameBox.addEvents({ focus: function() { if(firstNameBox.value == message) { searchBox.value = ''; } }, blur: function() { if(firstNameBox.value == '') { searchBox.value = message; } }});
placeholder
is another great addition to the browser and replaces the oldest snippet of JavaScript in the book! You can event !
placeholder
是浏览器的另一个重要补充,它取代了本书中最古老JavaScript代码段! 您可以使用事件 !
翻译自:
属性占位符