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屬性。

 

兩種方式的思路

  1. (方式一)使用input的value作為顯示文本
  2. (方式二)不使用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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM