JQ div随机显示背景色/取整函数/

上代码栗子

<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />

<script src="https://cdn.bootcss.com/jquery/3.0.0/jquery.min.js"></script>
<title>无标题文档</title>
<style>
    #box{
        width: 500px;
        height:500px;
        overflow: hidden;
        border: 1px solid #ddd
    }
    img{max-width: 100%;}
</style>
</head>
<script language="JavaScript">

function rand(number) {
    return Math.floor(Math.random()*number);
};

$(function(){
    var arr = ['red','blue','yellow','green','black','pink','orange'];
    var arrLength = arr.length;
    $('#box').css('backgroundColor',arr[rand(arrLength)]);  //取值0~6

})
</script>

<body>
    <div id="box"></div>
</body>
</html>

取整函数

function rand(number) {
    return Math.floor(Math.random()*number);
};

这里写图片描述

  • 数组索引是从0开始的
  • 如果是Math.round() 你会得到1-7 , 而不是0-6
  • div颜色可能会得到undefined
  • 用floor,可以得到0-6
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值