<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<svg id="s3" width="800" height="600" style="background-color: yellow">
</svg>
<script>
function rn(max,min) {
var num=Math.random()*(max-min)+min;
return Math.floor(num)
}
function cn(max,min) {
var r=rn(max,min)
var g=rn(max,min)
var b=rn(max,min)
return `rgb(${r},${g},${b})`
}
console.log(rn(0,256))
//創建一個循環30次
var s3=document.getElementById("s3")
for(var i=0;i<30;i++) {
//創建圓
var c = document.createElementNS(
"http://www.w3.org/2000/svg",
"circle"
);
c.setAttribute("r", rn(10, 80))
c.setAttribute("cx", rn(0, 800))
c.setAttribute("cy", rn(0, 600))
c.setAttribute("fill", cn(0, 256))
c.setAttribute("fill-opacity", rn(0, 10) * (0.1))
s3.appendChild(c)
c.onclick=function () {
//此處this指向的c
var that=this
//爲了防止圓被再次點擊,消息監聽函數
that.onclick=null
console.log(this)
var x=this.getAttribute("r")
var y=this.getAttribute("fill-opacity")
var t= setInterval(function(){
//定時器裏的this爲window
x++
y*=0.9
that.setAttribute("r",x)
that.setAttribute("fill-opacity",y)
if(y<0.001){
clearInterval(t)
s3.removeChild(that)
}
},100)
}
}
</script>
</body>
</html>