让Placeholder在IE中燥起来
2015-10-26 11:27 只喝牛奶的杀手 阅读(1204) 评论(6) 编辑 收藏 举报网上有好多关于这方面解决兼容性问题的文章,很多招式,学会这一招,让你轻松搞定Placeholder的兼容性,叫我好人,拿走,不谢。。。。
placeholder属性是HTML5 中为input添加的。在input上提供一个占位符,文字形式展示输入字段预期值的提示信息(hint),该字段会在输入为空时显示。
如
<input type="text" id="Title" class="so-input-d w270" placeholder="请输入标题" />
像下图用placeholder刚刚好,但是IE6 7 8 9 不支持呀,一篇空白!此时此刻心情肯定是日了狗!!!!!,搞web开发的一定要考虑兼容性,业界良心需要。。。。
使用前:
使用后:
疗效不一般,使用之后萌萌哒。
目前浏览器的支持情况:
浏览器 | IE6/7/8/9 | IE10+ | Firefox | Chrome | Safari |
是否支持 | NO | YES | YES | YES | YES |
下面分享一个Js文件代码,简单粗暴的把问题解决了:
( function ($) { $.fn.myPlaceholder = function (options) { var defaults = { pColor: "#acacac" , pFont: "16px" , posL: 8, zIndex: "99" }, opts = $.extend( true , defaults, options); if ( "placeholder" in document.createElement( "input" )) return ; return this .each( function () { //$(this).parent().css("position", "relative"); var isIE = $.browser.msie, version = $.browser.version; //不支持placeholder的浏览器 var $ this = $( this ), msg = $ this .attr( "placeholder" ), iH = $ this .outerHeight(), iW = $ this .outerWidth(), iX = $ this .offset().left, iY = $ this .offset().top, oInput = $( "<label>" , { "text" : msg, "css" : { "position" : "absolute" , "left" : iX + "px" , "top" : iY + "px" , "width" : iW - opts.posL + "px" , "padding-left" : opts.posL + "px" , "height" : iH + "px" , "line-height" : iH + "px" , "color" : opts.pColor, "font-size" : opts.pFont, "z-index" : opts.zIndex, "cursor" : "text" } }).insertBefore($ this ); //初始状态就有内容 var value = $ this .val(); if (value.length > 0) { oInput.hide(); }; var myEvent; if (isIE && version < 9) { myEvent = "propertychange" ; } else { myEvent = "input" ; } $ this .bind(myEvent, function () { var value = $( this ).val(); if (value.length > 0) { oInput.hide(); } else { oInput.show(); } }); oInput.click( function () { $ this .trigger( "focus" ); }); }); } })(jQuery); |
这是用JQUERY插件化思想的解决的!
在页面或者操作的Js文件只用这样轻轻一搞:
$(function () {
$("#Title").myPlaceholder();
});
Placeholder兼容问题就解决了(文章标红的地方注意ID一致)!
抓紧有限的时间,燥起来!
欢迎大家关注微信号killerhub,微信公众号名称:只喝牛奶的杀手, 扫下面的二维码或者收藏下面的二维码关注吧(长按下面的二维码图片、并选择识别图中的二维码)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端