【jquery】基于 jquery 实现 ie 浏览器兼容 placeholder 效果
placeholder 是 html5 新增加的屬性,主要提供一種提示(hint),用于描述輸入域所期待的值。該提示會(huì)在輸入字段為空時(shí)顯示,并會(huì)在字段獲得焦點(diǎn)時(shí)消失。placeholder 屬性適用于以下類型的 input 標(biāo)簽:text, search, url, telephone, email 以及 password。
我們先看下在谷歌瀏覽器中的效果,如圖所示:
獲得焦點(diǎn)時(shí):
輸入字段:
因?yàn)槭?html5 屬性,自然低版本的瀏覽器比如 ie6-8 不兼容。下面就介紹下如何在低版本瀏覽器中顯示以上效果,話不多說直接上代碼。
html:
<!doctype html> <html lang="en"> <head><meta charset="UTF-8"/><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/><meta name="renderer" content="webkit"/><meta name="keywords" content=""/><meta name="description" content=""/><title>基于 jquery 實(shí)現(xiàn) ie 瀏覽器兼容 placeholder 效果</title><style>*{margin:0;padding:0;}.txt{position:relative;font-size:12px;margin:10px;}.txt input{border:1px solid #ccc;height:30px;line-height:30px;padding:0 10px;width:200px;}.txt .txt-tip{color:#999;position:absolute;left:10px;top:0;height:32px;line-height:34px;}</style> </head> <body><div class="txt"><input type="text" value=""/></div> </body> </html> <script src="js/jquery.min.js"></script> <script src="js/placeholder.js"></script> <script> $(function(){var $input = $('.txt input');initPlaceholder($input, '請(qǐng)輸入內(nèi)容', 'txt-tip'); }); </script>placeholder.js:
function initPlaceholder($input, msg, classname){var isIE = !!window.ActiveXObject || 'ActiveXObject' in window;var isPlaceholder = 'placeholder' in document.createElement('input');if(isPlaceholder && !isIE){$input.attr('placeholder', msg);}else{var $tip = $('<span class="' + classname + '">' + msg + '</span>');$input.after($tip);$.data($input[0], 'tip', $tip);if($input.val() != ''){hidePHTip($input);}dealPHTip($input, $tip);} } function hidePHTip($input){var $tip = $.data($input[0], 'tip');if($tip){$tip.hide();} } function dealPHTip($input, $tip){var _deal = function(){var val = $input.val();if(val == ''){$tip.show();}else{$tip.hide();}};$tip.click(function(){$input.focus();});$input.on('input propertychange', function(){clearTimeout(timeout);var timeout = setTimeout(_deal, 0);}); }實(shí)現(xiàn)原理:首先過濾下瀏覽器,非 ie 瀏覽器并且支持 placeholder 屬性就用 placeholder,ie 瀏覽器則用 span 代替 placeholder 文本內(nèi)容,通過樣式定位在 input 上方,同時(shí)監(jiān)聽 input 輸入框值的變化來判斷顯示或隱藏 span。
我們來看下 ie6 瀏覽器中的效果:
獲得焦點(diǎn)時(shí):
輸入字段:
可以看到和谷歌瀏覽器的效果是一致的,唯一不足的就是文字沒有居中,可以通過 css 進(jìn)行修改。
總結(jié)
以上是生活随笔為你收集整理的【jquery】基于 jquery 实现 ie 浏览器兼容 placeholder 效果的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 嵌入式linux的学习笔记-共享内存(六
- 下一篇: web前端编程实现福彩投注站彩票投注助手