---
title: "jQuery模拟placeholder属性"
author: "bolinyang"
date: "2013-07-03T10:29:04Z"
tags: ["HTML", "IE", "jQuery"]
categories: ["Web前端"]
slug: "jquery-placeholder"
draft: false
lastmod: "2013-07-03T10:28:50Z"
id: 1897775
url: "https://bolinyang.iteye.com/blog/1897775"
---

一.概述
在使用HTML的input元素时，经常会用到placeholder属性。但是IE8不支持这个placeholder属性，有点悲催，只能使用js来模拟这个placeholder了

二.模拟placeholder的js代码

```java

if(!$.support.placeholder) {
	var els = $('input[placeholder],textarea[placeholder]');
	els.each(function(i, el) {
		el = $(el);
		var defValue = el.attr('placeholder'),
			defColor = el.css('color');
		el.bind('focus',function() {
			if(this.value === '' || this.value === defValue) {
				$(this).css('color', defColor);
				this.value = '';
			}
		});
		el.bind('blur',function() {
			if(this.value === '' || this.value === defValue) {
				$(this).css('color','#aaa');
				this.value = defValue;
			}
		});
		el.triggerHandler('blur');

		el.closest('form').submit(function(){
			var val = el.val();
			if(val === defValue){
				el.val('');
			}
		});
	});
}

```