zoukankan      html  css  js  c++  java
  • jQuery插件扩展实例

    1.index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>jQuery插件扩展实例</title>
        <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>  </head>
    <body>
    
    <p>徐同保</p>
    
    <script>
        //闭包限定命名空间
        (function ($) {
            //默认参数
            var defaluts = {
                foreground: 'red',
                background: 'yellow'
            };
            $.fn.extend({
                "highLight": function (options) {
                    //检测用户传进来的参数是否合法
                    if (!isValid(options)) {
                        return this;
                    }
                    //使用jQuery.extend 覆盖插件默认参数
                    var opts = $.extend({}, defaluts, options);
                    //这里的this 就是 jQuery对象。这里return 为了支持链式调用
                    //遍历所有的要高亮的dom,当调用 highLight()插件的是一个集合的时候。
                    return this.each(function () {
                        //获取当前dom 的 jQuery对象,这里的this是当前循环的dom
                        var $this = $(this);
                        //根据参数来设置 dom的样式
                        $this.css({
                            backgroundColor: opts.background,
                            color: opts.foreground
                        });
                        //格式化高亮文本
                        var markup = $this.html();
                        markup = $.fn.highLight.format(markup);
                        $this.html(markup);
                    });
    
                }
            });
            //公共的格式化 方法. 默认是加粗,用户可以通过覆盖该方法达到不同的格式化效果。
            $.fn.highLight.format = function (str) {
                return "<strong>" + str + "</strong>";
            };
            //私有方法,检测参数是否合法
            function isValid(options) {
                return !options || (options && typeof options === "object") ? true : false;
            }
        })(window.jQuery);
    
        //调用
        //调用者覆盖 插件暴露的共公方法
        $.fn.highLight.format = function (txt) {
            return "<em>" + txt + "</em>"
        };
    
        $(function () {
            $("p").highLight({ foreground: 'orange', background: '#ccc' }); //调用自定义 高亮插件
        });
    </script>
    </body>
    </html>

    2.运行结果


  • 相关阅读:
    Centos 8 部署harbor 访问502
    selenium学习记录
    shell基础
    抓取人民日报
    caffe在笔记本ubuntu10.04 64位下的无GPU安装
    【转】HMM
    typedef 的一些用法
    j2ee 使用tomcat开发网站需要访问中文名的资源遇到的问题解决方案。。
    解决lex.yy.c文件在vs2012下编译生成exe
    python学习
  • 原文地址:https://www.cnblogs.com/xutongbao/p/9924965.html
Copyright © 2011-2022 走看看