摘要:<!DOCTYPE html><html><head> <meta charset="utf-8"> <title></title> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script&g
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<style type="text/css">
a{float: left;display: inline-block;width: 100px;height: 100px;border-radius: 50%;background-color: red;line-height: 100px;text-align: center;text-decoration: none;cursor: pointer;margin-right: 10px;color: black}
</style>
<script type="text/javascript">
$(function(){
var c="rgb("+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+")";
$('a').each(function(){
$(this).css('background-color',"rgb("+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+")");
// $(this).css('background-color',"c");//此處不能是變量c 不然顏色一樣
})
$('a').hover(
function(){
var co=$(this).css('background-color');//獲取當(dāng)前的元素的顏色
$(this).css({'backgroundColor':co,'box-shadow':'0px 0px 20px'+co,'border-radius':'20%'});
},
function(){
var co=$(this).css('background-color');
$(this).css({'backgroundColor':co,'box-shadow':'none'+co,'border-radius':'50%'});
})
$('a').on('click',function(){
$(this).html(parseInt(Math.random()*999));
$(this).css({'backgroundColor':"rgb("+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+")"});
})
})
</script>
</head>
<body>
<div>
<a href="JavaScript:;">1</a>
<a href="JavaScript:;">2</a>
<a href="JavaScript:;">3</a>
</div>
</body>
</html>
疑問(wèn):
為什么文檔就緒函數(shù)下面的
var c="rgb("+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+")";
$('a').each(function(){
$(this).css('background-color',"rgb("+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+")");
上面的設(shè)置顏色為什么不能是預(yù)先定義的一個(gè)顏色,再設(shè)置呢 會(huì)是三個(gè)球球 顏色一樣;不是應(yīng)該是三種顏色的嗎
比如: $(this).css('background-color',"c");
這樣為什么不行?
})
批改老師:韋小寶批改時(shí)間:2019-02-22 10:54:14
老師總結(jié):因?yàn)槟莻€(gè)變量是在點(diǎn)擊事件外部 每次點(diǎn)擊 都會(huì)直接過(guò)去調(diào)用 你這樣改寫再看看
$('a').on('click',function(){
var c="rgb("+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+","+p