jQuery-randomColor插件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>randomColor</title>
    <script src="../../../jquery-3.4.1.min.js"></script>
    <style>
        div {
            float: left;
            width: 300px;
            height: 300px;
        }
    </style>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<script>
    /*要点:
    1,jQuery的插件另一在jQuery.fn的基础上的
    2,命名冲突的解决(参考https://www.cnblogs.com/RascallySnake/archive/2010/05/07/1729417.html
    3,循环jQuery对象中美俄元素
    4,在函数中,将jQuery返回(this)
    * */
    //要点2:语句块:解决命名冲突
    (function ($) {
        $.fn.extend({//要点1
            randomColor: function () {
                //this指向就是我们通过$选择器选取的所有元素组成的伪数组
                function random() {
                    var r = Math.floor(Math.random() * 256);//floor向下取整 0-255
                    var g = Math.floor(Math.random() * 256);
                    var b = Math.floor(Math.random() * 256);

                    return 'rgb(' + r + ',' + g + ',' + b + ')';
                }

                //要点3:循环每个jQuery对象
                this.each(function (index, element) {//index:索引值 element:元素本身
                    $(this).css({
                        backgroundColor: random()
                    });
                    console.log(index, element);
                });
                return this;//要点4,返回jQuery(this)
            }
        })
    })(jQuery);
    $('div').randomColor();
</script>
</body>
</html>

在这里插入图片描述

发布了13 篇原创文章 · 获赞 4 · 访问量 346

猜你喜欢

转载自blog.csdn.net/printf_hello/article/details/103939420