扩展jQuery方法

来源:互联网 发布:淘宝饰品详情页素材 编辑:程序博客网 时间:2024/06/05 19:18

css代码如下:

div {         width: 100px;         height: 100px;         border: 1px solid #000;         border-radius: 50%;         float: left;         margin: 10px;     }

html代码如下:

<div id="ball1"></div><div id="ball2"></div>

以上都不是最重要的,js代码如下:

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script><script>    /*        扩展jquery方法:        (1)$.fn.xxx  // 实例方法 fn相当于prototype        (2)$.xxx  // 静态方法        (3)$.fn.extend({xxx,xxx,....})        (4)$.extend({xxx,xxx,...})    */    // ---------------------$.fn.xxx---------------------    $.fn.changeColor = function () {        const red = Math.floor(Math.random() * 255)        const green = Math.floor(Math.random() * 255)        const blue = Math.floor(Math.random() * 255)        const color = 'rgb(' + red + ',' + green + ',' + blue + ')'        this.css('background', color)    }    function timer() {        $('#ball1').changeColor()        $('#ball2').changeColor()        setTimeout(function () {            timer()        }, 1000)    }    timer()    // --------------------$.extend({xxx})-----------------    $.extend({            hideborder : function (el) {                el.css('border','none')            },            showborder :function (el){                el.css('border','1px solid #000')            }    })    $('div').hover(        function(){            $.hideborder($(this))        },        function(){            $.showborder($(this))        }    )</script>

两种方法的不同在于一个实例上的扩展,一个是原型上的扩展

原创粉丝点击