如何使用 HTML5 占位符属性并考虑到向后兼容性?
我想使用 HTML5 的占位符属性(您可以在 思考结果)。但是,当我使用旧版浏览器时,它们当然不会呈现任何内容。我可以使用 JavaScript 来模仿它,但是,我不应该使用它,它是用旧的方式完成的。我怎样才能拥有 HTML5 占位符属性,同时为旧版浏览器模拟它?
I'd like to use HTML5's placeholder attribute (You can see it in cation in the newsletter at Thought Results). But when I use older browsers, of course, they don't render anything. I can use JavaScript to imitate it, but then, I shouldn't use it and it's done the old way. How can I have both HTML5 placeholder attribute, and at the same time simulate it for older browsers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以检测浏览器是否支持该属性:
http://diveintohtml5.info/detect.html#input -placeholder
如果是,则不执行任何操作。如果没有,您可以使用 JS 获取占位符值,然后将其插入到您认为合适的字段中(可能作为默认值),然后添加适当的交互来模拟 HTML5 占位符行为。
You can detect if a browser supports the attribute:
http://diveintohtml5.info/detect.html#input-placeholder
If it does, do nothing. If it doesn't, you can use JS to grab the placeholder value and then insert it into the field as you see fit (perhaps as default value) and then add the appropriate interactions to simulate the HTML5 placeholder behaviors.
@marcgg 编写了一个很棒的 JQuery 占位符插件,它基本上为那些不支持它的浏览器复制了占位符功能。
https://github.com/marcgg/Simple-Placeholder
我搜索了很多占位符在决定使用这个插件之前,我先安装了一些插件,到目前为止效果很好。最初发现它是为了回答类似的问题:
https://stackoverflow.com/questions/5120257/what-is-the-best-html5-placeholder-like-jquery-plugin-out-there
@marcgg wrote a great JQuery placeholder plugin that basically replicates the placeholder functionality for those browsers that don't support it.
https://github.com/marcgg/Simple-Placeholder
I searched through a lot of placeholder plugins before settling on this one and it works great so far. Originally found it in response to this similar question:
https://stackoverflow.com/questions/5120257/what-is-the-best-html5-placeholder-like-jquery-plugin-out-there
我建议使用 Modernizr 来检测此功能。
如果您对使用此库不感兴趣,可以使用以下代码。
关于后备支持,如果您使用 jQuery,您可以使用 Simple Placeholder,它有其起源于StackOverflow。
I recommend using Modernizr to detect this feature.
If you're not interested in using this library you could use the following the code.
Regarding to fallback support, if you're using jQuery you could use Simple Placeholder, which had its origin here at StackOverflow.