摘要:Math.random() 獲取隨機(jī)數(shù)Math.floor 取整數(shù)例:function aa(tag){ //獲取隨機(jī)顏色 var len=document.getElementsByTagName(tag).length
Math.random() 獲取隨機(jī)數(shù)
Math.floor 取整數(shù)
例:
function aa(tag){ //獲取隨機(jī)顏色
var len=document.getElementsByTagName(tag).length
for(i=0;i<len;i++){
document.getElementsByTagName(tag)[i].style.backgroundColor='rgb('+Math.floor(Math.random()*256)+','+Math.floor(Math.random()*256)+','+Math.floor(Math.random()*256)+')'
}
總結(jié):首先獲取到a標(biāo)簽點(diǎn)長度!然后for循環(huán)輸出設(shè)置每個(gè)a標(biāo)簽的背景色!用Math.random來做獲取隨機(jī)數(shù)!
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="/jQuery/jQuery-3.3.1.js"></script> <style> a{border-radius: 50px; float: left;display: block;height: 50px;width: 50px;margin-top: 50px;margin-left: 50px;line-height: 50px;text-align: center;color: aqua;} </style> <script> function aa(tag){ //獲取隨機(jī)顏色 var len=document.getElementsByTagName(tag).length for(i=0;i<len;i++){ document.getElementsByTagName(tag)[i].style.backgroundColor='rgb('+Math.floor(Math.random()*256)+','+Math.floor(Math.random()*256)+','+Math.floor(Math.random()*256)+')' } } function h(c){ //獲取隨機(jī)值 var l=document.getElementsByTagName(c).length for(i=0;i<l;i++){ document.getElementsByTagName(c)[i].innerHTML=Math.floor(Math.random()*10) } } $(function(){ aa('a') $('.bt1').click(function(){ //調(diào)用上面的獲取隨機(jī)顏色的函數(shù) aa('a') }); $('.bt2').click(function(){ // $s=Math.floor(Math.random()*5) // $('a').text($s) //這兩行代碼可以改變隨機(jī)值但是是四個(gè)a標(biāo)簽值統(tǒng)一改變!我不想統(tǒng)一改變 h('a') }); $('.bt3').click(function(){ aa('a'); h('a') }) $('a').mouseover(function(){ $bg=$(this).css('backgroundColor') $(this).css('box-shadow','0px 0px 10px '+$bg) $(this).css('borderRadius','20px') }) $('a').mouseleave(function(){ $(this).css('box-shadow','none') $(this).css('borderRadius','50px') }) }) </script> </head> <body> <a href="#">1</a> <a href="#">2</a> <a href="#">3</a> <a href="#">4</a> <button class="bt1">隨機(jī)色</button> <button class="bt2">隨機(jī)值</button> <button class="bt3">隨機(jī)色+隨機(jī)值</button> </body> </html>
批改老師:查無此人批改時(shí)間:2019-01-14 16:15:22
老師總結(jié):完成的不錯(cuò)。下次把代碼縮進(jìn),查看起來比較方便,養(yǎng)成好習(xí)慣。加油。