使用JavaScript函数生成的随机数作为rgb颜色的应用

xiaoxiao2021-07-04  294

本文开始:

需要用到的函数:Math.random、document.getElementsByClassName()、parsetInt() 需要用到的语言:html、JavaScript、css

关键代码如下:

//head部分 </head> <style type="text/css"> //给div设置样式 .top{ width: 500px; height:400px; margin:auto; } </style> </head> //body部分 <body> <div class="top"> //设置按钮,用来按下改变背景颜色 <button onclick="changeClolor()"> 按下变颜色 </button> </div> </body> //JavaScript部分 <script type="text/javascript"> function changeClolor(){ //这是三个0-255之间的随机数的生成,并储存下来 var numone=parseInt(Math.random()*(255+1),10); var numtwo=parseInt(Math.random()*(255+1),10); var numthree=parseInt(Math.random()*(255+1),10); //获取class名字为top的节点 var changediv=document.getElementsByClassName("top"); /*设置class名字为top的节点背景颜色用rgb表示,因为用background设置的方式必须使用字符串, 所以必须将获取的随机数用字符串拼接起来,再赋值给background属性*/ changediv[0].style.background="rgb("+numone+","+numtwo+","+numthree+")"; } </script>
转载请注明原文地址: https://www.6miu.com/read-4821289.html

最新回复(0)