面向对象实现点击生成随机颜色大小的方块

面向对象实现点击生成随机颜色大小的方块

>

实现效果: 点击页面任意地方 会生成一个随机大小的颜色快
在这里插入图片描述

  <script>
        class Rc {

            constructor() {
                document.body.addEventListener('click', this.getBox.bind(this))
                // console.log(this)
            }

            getBox(e) {
                //生成一个区间的随机数 这个值是div的宽和高
                let wh = this.random(150, 200)

                //.获取鼠标的坐标 - 宽高的一般 指针在div的中间
                let x = e.clientX - wh / 2
                let y = e.clientY - wh / 2
                //创建属性 属性值
                this.creatElement('div', {
                    position: 'absolute',
                    left: x + 'px',
                    top: y + 'px',
                    background: this.color(),
                    width: wh + 'px',
                    height: wh + 'px'
                })
              
            }

            //创建元素

            creatElement(ele, styleObj) {
                let newEle = document.createElement(ele, styleObj)

                //样式合并在一起
                Object.assign(newEle.style,styleObj)
                //追加到body里面
                document.body.appendChild(newEle)

            }
            //封装随机数
            random(x, y) {
                let n = Math.max(x, y)
                let m = Math.min(x, y)
                return parseInt(Math.random() * (n - m) + m)
            }
            //封装随机颜色
            color() {
                let arr = []
                for (let i = 0; i < 3; i++) {
                    let items = this.random(0, 255)
                    arr.push(items)
                }
                var transparent = Math.random().toFixed(1) //透明度
                //拼接rgb
                return  `rgb(${arr[0]},${arr[1]},${arr[2]},${transparent})`
            }

        }

          let l = new Rc()
        // let res =  l.random(80, 100)
        // console.log(res)
        console.log(l.color())

注意

这里要在css里面给html和body设置宽高为100% 不然点击不了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值