class es6面向对象,生成随机大小,颜色,位置的小球

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>生成随机大小,颜色,位置的小球</title>
    <style>
        .btn {
            width: 80px;
            height: 20px;
            text-align: center;
            line-height: 20px;
            border-radius: 6px;
            background-color: #eeee;
            cursor: pointer;
        }

        .app {
            width: 1000px;
            height: 800px;
            border: 1px solid red;
            border-radius: 12px;
            position: relative;
        }

        .boo {
            display: inline-block;
            border-radius: 50%;
            position: absolute;
        }
    </style>
</head>
<body>
<div class="btn">创建小球</div>
<div class="app"></div>
<script>
    class Boo {
        constructor() {
            this.init()
        }
        init() {
            // 创建一个小球
            // 小球大小随机,背景色随机,位置随机
            this.createBol()
        }

        getRandomWidthHeight() {
            return Math.floor(Math.random() * 51);
        }

        getRandomLeft() {
            return Math.round(Math.random()*999+1);
        }

        getRandomTop() {
            return Math.round(Math.random()*799+1);
        }

        getRandomRgb() {
            let r = Math.floor(Math.random()*256)
            let g = Math.floor(Math.random()*256)
            let b = Math.floor(Math.random()*256)
            let rgb = `rgb(${r},${g},${b})`
            return rgb
        }

        createBol() {
            let app = document.getElementsByClassName('app')[0]
            let boo = document.createElement('span')
            let wh = this.getRandomWidthHeight() + 'px'
            boo.style.width = wh
            boo.style.height = wh
            boo.className='boo'
            boo.style.backgroundColor = this.getRandomRgb()
            boo.style.left= this.getRandomLeft() + 'px'
            boo.style.top= this.getRandomTop() + 'px'
            app.append(boo)
        }
    }
    
    let btn = document.getElementsByClassName('btn')[0]
    btn.addEventListener('click', function () {
        let boo = new Boo(20, 30)
    })
</script>
</body>
</html>
创建随机大小的数字
Math.round(Math.random()*(max-min)+min);
创建随机背景色
getRandomRgb() {
            let r = Math.floor(Math.random()*256)
            let g = Math.floor(Math.random()*256)
            let b = Math.floor(Math.random()*256)
            let rgb = `rgb(${r},${g},${b})`
            return rgb
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容