PlaceHolder的两种实现方式
placeholder属性是HTML5 中为input添加的。在input上提供一个占位符,文字形式展示输入字段预期值的提示信息(hint),该字段会在输入为空时显示。
如
<input type="text" name="loginName" placeholder="邮箱/手机号/QQ号">
目前浏览器的支持情况
| 浏览器 | IE6/7/8/9 | IE10+ | Firefox | Chrome | Safari |
| 是否支持 | NO | YES | YES | YES | YES |
然而,虽然IE10+支持placeholder属性,它的表现与其它浏览器也不一致
- IE10+里鼠标点击时(获取焦点)placeholder文本消失
- Firefox/Chrome/Safari点击不消失,而是键盘输入时文本消失
这相当恶心,如果使用了placeholder属性。产品经理还是不依不饶,会讲为什么IE里是点击的时候提示文本消失,Chrome里却是键盘输入的时候提示文本消失。要求前端工程师改成一样的表现形式。鉴于此,以下两种实现方式均不采用原生的placeholder属性。
两种方式的思路
- (方式一)使用input的value作为显示文本
- (方式二)不使用value,添加一个额外的标签(span)到body里然后绝对定位覆盖到input上面
两种方式各有优缺点,方式一占用了input的value属性,表单提交时需要额外做一些判断工作,方式二则使用了额外的标签。
方式一
/**
* PlaceHolder组件
* $(input).placeholder({
* word: // @string 提示文本
* color: // @string 文本颜色
* evtType: // @string focus|keydown 触发placeholder的事件类型
* })
*
* NOTE:
* evtType默认是focus,即鼠标点击到输入域时默认文本消失,keydown则模拟HTML5 placeholder属性在Firefox/Chrome里的特征,光标定位到输入域后键盘输入时默认文本才消失。
* 此外,对于HTML5 placeholder属性,IE10+和Firefox/Chrome/Safari的表现形式也不一致,因此内部实现不采用原生placeholder属性
*/
$.fn.placeholder = function(option, callback) {
var settings = $.extend({
word: '',
color: '#ccc',
evtType: 'focus'
}, option) function bootstrap($that) {
// some alias
var word = settings.word
var color = settings.color
var evtType = settings.evtType // default
var defColor = $that.css('color')
var defVal = $that.val() if (defVal == '' || defVal == word) {
$that.css({color: color}).val(word)
} else {
$that.css({color: defColor})
} function switchStatus(isDef) {
if (isDef) {
$that.val('').css({color: defColor})
} else {
$that.val(word).css({color: color})
}
}
function asFocus() {
$that.bind(evtType, function() {
var txt = $that.val()
if (txt == word) {
switchStatus(true)
}
}).bind('blur', function() {
var txt = $that.val()
if (txt == '') {
switchStatus(false)
}
})
}
function asKeydown() {
$that.bind('focus', function() {
var elem = $that[0]
var val = $that.val()
if (val == word) {
setTimeout(function() {
// 光标定位到首位
$that.setCursorPosition({index: 0})
}, 10)
}
})
} if (evtType == 'focus') {
asFocus()
} else if (evtType == 'keydown') {
asKeydown()
} // keydown事件里处理placeholder
$that.keydown(function() {
var val = $that.val()
if (val == word) {
switchStatus(true)
}
}).keyup(function() {
var val = $that.val()
if (val == '') {
switchStatus(false)
$that.setCursorPosition({index: 0})
}
})
} return this.each(function() {
var $elem = $(this)
bootstrap($elem)
if ($.isFunction(callback)) callback($elem)
})
}
线上示例:http://snandy.github.io/lib/ui/demo/placeholder/b.html
会用到 setCursorPosition。
方式二
$.fn.placeholder = function(option, callback) {
var settings = $.extend({
word: '',
color: '#999',
evtType: 'focus',
zIndex: 20,
diffPaddingLeft: 3
}, option)
function bootstrap($that) {
// some alias
var word = settings.word
var color = settings.color
var evtType = settings.evtType
var zIndex = settings.zIndex
var diffPaddingLeft = settings.diffPaddingLeft
// default css
var width = $that.outerWidth()
var height = $that.outerHeight()
var fontSize = $that.css('font-size')
var fontFamily = $that.css('font-family')
var paddingLeft = $that.css('padding-left')
// process
paddingLeft = parseInt(paddingLeft, 10) + diffPaddingLeft
// redner
var $placeholder = $('<span class="placeholder">')
$placeholder.css({
position: 'absolute',
zIndex: '20',
color: color,
width: (width - paddingLeft) + 'px',
height: height + 'px',
fontSize: fontSize,
paddingLeft: paddingLeft + 'px',
fontFamily: fontFamily
}).text(word).hide()
// 位置调整
move()
// textarea 不加line-heihgt属性
if ($that.is('input')) {
$placeholder.css({
lineHeight: height + 'px'
})
}
$placeholder.appendTo(document.body)
// 内容为空时才显示,比如刷新页面输入域已经填入了内容时
var val = $that.val()
if ( val == '' && $that.is(':visible') ) {
$placeholder.show()
}
function hideAndFocus() {
$placeholder.hide()
$that[0].focus()
}
function move() {
var offset = $that.offset()
var top = offset.top
var left = offset.left
$placeholder.css({
top: top,
left: left
})
}
function asFocus() {
$placeholder.click(function() {
hideAndFocus()
// 盖住后无法触发input的click事件,需要模拟点击下
setTimeout(function(){
$that.click()
}, 100)
})
// IE有些bug,原本不用加此句
$that.click(hideAndFocus)
$that.blur(function() {
var txt = $that.val()
if (txt == '') {
$placeholder.show()
}
})
}
function asKeydown() {
$placeholder.click(function() {
$that[0].focus()
})
}
if (evtType == 'focus') {
asFocus()
} else if (evtType == 'keydown') {
asKeydown()
}
$that.keyup(function() {
var txt = $that.val()
if (txt == '') {
$placeholder.show()
} else {
$placeholder.hide()
}
})
// 窗口缩放时处理
$(window).resize(function() {
move()
})
// cache
$that.data('el', $placeholder)
$that.data('move', move)
}
return this.each(function() {
var $elem = $(this)
bootstrap($elem)
if ($.isFunction(callback)) callback($elem)
})
}
线上示例:http://snandy.github.io/lib/ui/demo/placeholder/a.html
方式2 对于以下场景不适合
1. input初始隐藏
此时无法取到input的offset,继而无法定位span到input上面。
2. 包含input的页面dom结构发生变化
比如页面里删除了一些元素或添加了一些元素,导致input向上或向下偏移,而此时span则没有偏移(span相对body定位)。这比较恶心,可以考虑把span作为input的兄弟元素,即相对内层div定位(而不是body)。但这样必须强制给外层div添加position:relative,添加后可能会对页面布局产生一定影响。
相关:
http://www.w3.org/TR/2009/WD-html5-20090825/forms.html#the-placeholder-attribute
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-placeholder
PlaceHolder的两种实现方式的更多相关文章
- Web APi之认证(Authentication)两种实现方式【二】(十三)
前言 上一节我们详细讲解了认证及其基本信息,这一节我们通过两种不同方式来实现认证,并且分析如何合理的利用这两种方式,文中涉及到的基础知识,请参看上一篇文中,就不再叙述废话. 序言 对于所谓的认证说到底 ...
- Android中BroadcastReceiver的两种注册方式(静态和动态)详解
今天我们一起来探讨下安卓中BroadcastReceiver组件以及详细分析下它的两种注册方式. BroadcastReceiver也就是"广播接收者"的意思,顾名思义,它就是用来 ...
- Android中Fragment与Activity之间的交互(两种实现方式)
(未给Fragment的布局设置BackGound) 之前关于Android中Fragment的概念以及创建方式,我专门写了一篇博文<Android中Fragment的两种创建方式>,就如 ...
- JavaScript 函数的两种声明方式
1.函数声明的方式 JavaScript声明函数有两种选择:函数声明法,表达式定义法. 函数声明法 function sum (num1 ,num2){ return num1+num2 } 表达式定 ...
- Redis两种持久化方式(RDB&AOF)
爬虫和转载请注明原文地址;博客园蜗牛:http://www.cnblogs.com/tdws/p/5754706.html Redis所需内存 超过可用内存怎么办 Redis修改数据多线程并发—Red ...
- struts2+spring的两种整合方式
也许有些人会因为学习了struts1,会以为struts2.struts1与spring的整合也是一样的,其实这两者相差甚远.下面就来讲解一下struts2与spring的整合两种方案.(部分转载,里 ...
- easyui datagride 两种查询方式
easyui datagride 两种查询方式function doReseach() { //$('#tt').datagrid('load', { // FixedCompany: $('.c_s ...
- 【Visual Lisp】两种出错处理方式
两种出错处理方式:一种是对出错函数进行重定义,一种是对错误进行捕捉处理. ;;============================================================= ...
- 两种include方式及filter中的dispatcher解析
两种include方式 我自己写了一个original.jsp,另外有一个includedPage.jsp,我想在original.jsp中把includedPage.jsp引进来有两种方式: 1.& ...
随机推荐
- Lock的实现之ReentrantLock详解
摘要 Lock在硬件层面依赖CPU指令,完全由Java代码完成,底层利用LockSupport类和Unsafe类进行操作: 虽然锁有很多实现,但是都依赖AbstractQueuedSynchroniz ...
- [python拾遗]文件操作
文件操作 1.open()函数 open()函数主要用于文件处理,一般分为下面3个过程: 1.打开文件 2.操作文件 3.关闭文件 常见的格式示例: f = open('note.txt','r') ...
- jquery的insertBefore(),insertAfter(),after(),before()
insertBefore():a.insertBefore(b) a在前,b在后, a:是一个选择器,b:也是一个选择器 <!DOCTYPE html> <html> < ...
- jQuery Danmmu Player 弹幕视频
Danmmu Player是基于jQuery的弹幕视频插件.当在看视频的时候,同时发表自己的观点,这样很好的提高用户互动效果.其实也就是在视频界面上做一个滚动展示动画效果,这样的聊天互动视频效果我们叫 ...
- TaggingJS – 可以灵活定制的 jQuery 标签系统插件
TaggingJS 是一款 jQuery 插件,用来创建高度可定制的前端标签系统.这款插件不到3KB ,支持主流浏览器.有几种方法来定制 TaggingJS 的默认行为:一是使用 custom_op ...
- 类似 Dribbble 下载按钮的 SVG 弹性动画进度条
Codrops 发布了一个如何创建一个基于弹性效果的 SVG 加载进度条教程,基于 SVG 和 TweenMax 实现.按钮开始的时候是一个带有箭头的图标,一旦它被点击,动画成一个有趣的小金属丝和一个 ...
- MySQL之MySQL5.7中文乱码
自己的MySQL服务器不能添加中文,于是自己使用 show variables like 'character%'; 查看了当前的编码格式 我又通过以下方法将其设置为utf-8 SETcharacte ...
- 原生JS实现轮播+学前端的感受(防止走火入魔)
插件!插件!天天听到有人求这个插件,那个插件的,当然,用第三方插件可以大幅提高开发效率,但作为新手,我还是喜欢自己来实现,主要是我有时间! 今天我来给大家分享下用原生JS实现图片轮播的写法 前辈们可以 ...
- Web前端面试题目汇总
以下是收集一些面试中经常会遇到的经典面试题以及自己面试过程中有一些未解决的问题,通过对知识的整理以及经验的总结,重新巩固自身的前端基础知识,如有错误或更好的答案,欢迎指正,水平有限,望各位不吝指教.: ...
- 不直接登录SharePoint服务器,通过远程直接部署WSP解决方案包
在这之前不得不说一下Sysinternals,他最初是一个网站,网站上会经常发布一些有用的系统扩展工具,之后运营这个网站的公司被微软收购.像非常著名的Procmon,AutoRuns.Process ...