• jQuery placeholder插件 让IE也能够支持placeholder属性


    jQuery placeholder插件 让IE也能够支持placeholder属性

    案例:整搜索框,需要默认占位符为“请输入关键词”,获取焦点时,占位符消失或不可用(不影响正常输入),丢失焦点后,若用户无内容输入,占位符继续出现,继续占位。这种代码我想前端们已经很容易就写出来了吧,现在HTML5原生就有这个“placeholder”属性,效果与上边案例描述的一样(各支持的浏览器内部表现可能不一致,但是作用是一致的),那么这一属性该怎么优雅降级到支持所有现代浏览器呢?答案还是脚本即JavaScript。

    ;(function ($) {
        $.fn.extend({
            placeholder : function () {
                if ("placeholder" in document.createElement("input")) {
                    return this //如果原生支持placeholder属性,则返回对象本身
                } else {
                    return this.each(function () {
                        var _this = $(this);
                        _this.val(_this.attr("placeholder")).focus(function () {
                            if (_this.val() === _this.attr("placeholder")) {
                                _this.val("")
                            }
                        }).blur(function () {
                            if (_this.val().length === 0) {
                                _this.val(_this.attr("placeholder"))
                            }
                        })
                    })
                }
            }
        })
    })(jQuery);

    通过脚本判断浏览器是否原生支持placeholder属性来动态加载这个脚本

    if(!"placeholder" in document.createElement("input")){
        $.getScript("jquery.placeholder.js",function(){
            $("#keyword").placeholder();//让id=keyword的元素支持placeholder,换成你自己的选择器
        })
    }
  • 相关阅读:
    寒假学习记录07
    寒假学习记录06
    寒假学习记录05
    寒假学习记录04
    寒假学习记录03
    寒假学习记录02
    寒假学习记录01
    河北省重大技术需求征集系统(13)
    学习进度(4)
    学习进度(3)
  • 原文地址:https://www.cnblogs.com/weixin186/p/5162251.html
Copyright © 2020-2023  润新知