欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

placeholder兼容 浏览器placeholder兼容 

程序员文章站 2022-06-09 19:44:41
...
//兼容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[i],
                        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");