---
title: "placeholder兼容 "
author: "pigaps"
date: "2015-04-03T18:04:01Z"
tags: []
categories: ["Web前端"]
slug: "placeholder"
draft: false
lastmod: "2015-04-03T18:04:01Z"
id: 2199237
url: "https://pigaps.iteye.com/blog/2199237"
---

//兼容placeholder nodes： 需要兼容的元素，placeholder里面字体的颜色
    function placeholder(nodes, itemColor) {
        /**
         * 判断浏览器是否支持placeholder
         *  !("placeholder" in document.createElement("input") ----浏览器不支持placeholder属性
         */
        if (nodes.length && !("placeholder" in document.createElement("input"))) {
            for (var i = 0; i < nodes.length; i++) {//遍历需要添加placeholder的元素
                var self = nodes*,
                        placeholder = self.getAttribute('placeholder') || '';//获取placeholder属性的值
                //绑定onfocus事件（焦点事件：清空placeholder的值和颜色）
                self.onfocus = function () {
                    if (self.value == placeholder) {
                        self.value = '';
                        self.style.color = '';
                    }
                }
                //绑定onblur事件（赋值和添加颜色）
                self.onblur = function () {
                    if (self.value == "") {
                        self.value = placeholder;
                        self.style.color = itemColor;
                    }
                }
                //没有点击事件时
                self.value = placeholder;//赋值
                self.style.color = itemColor;//添加颜色
            }
        }
    }
    var item = document.getElementsByTagName('input');
    placeholder(item, "red");