zl程序教程

您现在的位置是:首页 >  后端

当前栏目

js给div设置随机色demo示例

JS 设置 示例 随机 Demo div
2023-09-14 09:04:05 时间
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>随机色</title>
        <script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
        <script type="text/javascript">
            // function get_random_color() {    //方法2不能用
            //     var letters = '0123456789ABCDEF'.split('');
            //     var color = '#';
            //     for (var i = 0; i < 6; i++ ) {
            //         color += letters[Math.round(Math.random() * 15)];
            //     }

            //     return color;
            // }
            // $(".random").each(function() {
            //     $(this).css("background-color", get_random_color());
            // });

            $(function() {   //方法一
                $(".random").each(function() {
                    var random = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ')';
                     $(this).css("background-color", random);
                });
            });
            
        </script>
    </head>
    <body>
        <div class="random">随机色</div>
        <div class="random">随机色</div>
        <div class="random">随机色</div>
        <div class="random">随机色</div>
        <div class="random">随机色</div>
        <div class="random">随机色</div>
        <div class="random">随机色</div>
        <div class="random">随机色</div>
        <div class="random">随机色</div>
        <div class="random">随机色</div>
        <div class="random">随机色</div>
        <div class="random">随机色</div>
        <div class="random">随机色</div>
    </body>
</html>

在这里插入图片描述