class es6面向?qū)ο?,生成隨機大小,顏色,位置的小球

<!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">創(chuàng)建小球</div>
<div class="app"></div>
<script>
    class Boo {
        constructor() {
            this.init()
        }
        init() {
            // 創(chuàng)建一個小球
            // 小球大小隨機,背景色隨機,位置隨機
            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},$)`
            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>
創(chuàng)建隨機大小的數(shù)字
Math.round(Math.random()*(max-min)+min);
創(chuàng)建隨機背景色
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},$)`
            return rgb
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容