サマリー:基本思路(1)使用JavaScript的Math.floor(Math.random()*256)方法獲取一個(gè)0~256的隨機(jī)數(shù),將隨機(jī)數(shù)賦予RGB顏色模式rgb()方法獲得一個(gè)隨機(jī)顏色。(2)使用document.getElementsByTagName('a')獲取元素?cái)?shù)量,然后用for循環(huán)給每個(gè)元素添加顏色。el = document.getElement
基本思路
(1)使用JavaScript的Math.floor(Math.random()*256)方法獲取一個(gè)0~256的隨機(jī)數(shù),將隨機(jī)數(shù)賦予RGB顏色模式rgb()方法獲得一個(gè)隨機(jī)顏色。
(2)使用document.getElementsByTagName('a')獲取元素?cái)?shù)量,然后用for循環(huán)給每個(gè)元素添加顏色。
el = document.getElementsByTagName('a') for (var i=0; i<el.length; i++) { var r = Math.floor(Math.random()*256) var g = Math.floor(Math.random()*256) var b = Math.floor(Math.random()*256) el[i].style.backgroundColor='rgb('+r+','+g+','+b+')' //串聯(lián),使用單引號(hào)/雙引號(hào),不要混用 }
(3)獲取上一步賦予顏色,將其設(shè)置為box-shadow的顏色。jQuery使用【$】聲明變量,調(diào)用時(shí)同樣帶有該標(biāo)識(shí)。
$('a').mouseover(function(){ $cl = $(this).css('backgroundColor') //獲取現(xiàn)有顏色 $(this).css('box-shadow','0px 0px 20px '+$cl) //必須要有空格 $(this).css('borderRadius','20px') })
注意事項(xiàng)
(1)使用rgb()設(shè)置顏色時(shí),rgb()應(yīng)由引號(hào)包裹,整體視為字符串;沒有引號(hào)則當(dāng)作函數(shù)處理,出現(xiàn)not defined錯(cuò)誤。
(2)數(shù)字與字符通過+串聯(lián),類型為string,所以在backgroundColor='rgb('+r+','+g+','+b+')'中,外部不需要再加引號(hào);$(this).css('box-shadow','0px 0px 20px ·'+$cl)中的【·】處必須有空格,作為字符串的一部分。
(3)函數(shù)傳參
定義一個(gè)獲取節(jié)點(diǎn)列表的函數(shù),將tagName設(shè)置為含數(shù)參數(shù);調(diào)用函數(shù)時(shí),將標(biāo)簽名作為參數(shù)傳入,即可獲得對(duì)應(yīng)標(biāo)簽的列表。
<script type="text/javascript"> function getEl(tag){ el = document.getElementsByTagName(tag) } getEl() //參數(shù)為tagName,如'a'/'p' </script>
完整代碼
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>jQuery獲取隨機(jī)顏色</title> <script src="js/jquery-3.3.1.js"></script> <style type="text/css"> a{text-align: center; text-decoration: none; color: white; display: block; float: left; line-height: 100px; width: 100px; height: 100px; border-radius: 50px; margin: 5px 5px;} </style> </head> <body> <a href="#">1</a> <a href="#">2</a> <a href="#">3</a> <a href="#">4</a> <script type="text/javascript"> el = document.getElementsByTagName('a') // el[1].style.background='rgb(255,230,220)' // Math.floor(Math.random()*256) for (var i=0; i<el.length; i++) { var r = Math.floor(Math.random()*256) var g = Math.floor(Math.random()*256) var b = Math.floor(Math.random()*256) el[i].style.backgroundColor='rgb('+r+','+g+','+b+')' } $('a').mouseover(function(){ $cl = $(this).css('backgroundColor') //獲取現(xiàn)有顏色 $(this).css('box-shadow','0px 0px 20px '+$cl) //必須要有空格,字符串的一部分 // $(this).css('borderColor','white') $(this).css('borderRadius','20px') }) $('a').mouseleave(function(){ $(this).css('box-shadow','none') // $(this).css('border','none') $(this).css('borderRadius','50px') }) </script> </body> </html>
END
添削の先生:韋小寶添削時(shí)間:2018-11-17 09:10:35
先生のまとめ:嗯!寫的很不錯(cuò)!這兩天的作業(yè)一直很棒!不要驕傲!繼續(xù)加油吧!