<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
//将页面颜色更改为黑色
document.body.style.backgroundColor = '#000'
//创建鼠标点击事件并执行生成图片的函数
document.onclick = function generate(event) {
//创建img标签
let img = document.createElement("img")
//填入图片地址
img.src = "0.gif"
img.style.position = 'absolute'
//将创建好的图片添加进body中
document.body.appendChild(img)
//创建加载事件
img.onload = function() {
//当图片加载好后获取源图片的宽高
const gat_img_w = parseInt(getComputedStyle(img).width)
const gat_img_h = parseInt(getComputedStyle(img).height)
//调用随机生成数函数并赋值给h使其充当图片的高 并按比例计算出图片的高
w = gatRandom(500, 20)
h = gat_img_w / gat_img_h * w
//将随机的宽高赋值给将要生成的图片
img.style.width = w + 'px'
img.style.height = h +'px'
//从event对象中获取鼠标的位置并赋值给将要生成的图片
img.style.left = (event.pageX - w / 2) + "px"
img.style.top = (event.pageY - h / 2) + "px"
}
}
//创建一个能够在某个区间随机生成数字的函数
function gatRandom(max, min) {
return min + Math.ceil(Math.random() * (max - min))
}
</script>
</body>
</html>
抽奖
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style>
//使用通用选择器将标签的内外边距设置为0
* {
margin: 0px;
padding: 0px;
}
</style>
<body>
<div id="container"></div>
<script>
//获取div标签并添加样式
let div = document.getElementById("container")
div.style.height = 1500 + "px"
div.style.width = 1000 + "px"
div.style.border = "1px solid red"
div.style.margin = "auto"
div.style.textAlign = "center"
//创建圆形的背景图
let circle = document.createElement("div")
circle.style.height = 500 + "px"
circle.style.width = 500 + "px"
circle.style.backgroundColor = "red"
circle.style.margin = "auto"
circle.style.borderRadius = "50%"
circle.textContent = "太阳"
circle.style.color = "white"
circle.style.fontSize = 50 + "px"
circle.style.lineHeight = 500 + "px"
circle.style.textAlign = "center"
//将创建好的背景图添加进document
div.appendChild(circle)
//创建按钮
let button = document.createElement("button")
button.innerText = "随机选择出生地"
button.style.height = 100 + "px"
button.style.width = 500 + "px"
button.style.fontSize = 50 + "px"
button.style.margin = "auto"
button.style.marginTop = 40 + "px"
//给按钮添加点击事件
button.onclick = function(){
//当按钮点击按钮后字符从"随机选择出生地"变为"停止"
if(staert == "随机选择出生地"){
staert = "停止"
//调用创建好的随机选取函数让其定时执行
id = setInterval(random,10)
//当按钮点击按钮后字符从"停止"变为"随机选择出生地"
}else if(staert == "停止"){
//将staert中的内容修改为"随机选择出生地" 让其下一次点击时可以填入到按钮中
staert = "随机选择出生地"
//将按钮中的内容改为"随机选择出生地"
button.innerText = "随机选择出生地"
//停止定时器
clearInterval(id)
}
}
div.appendChild(button)
//定义一个变量
let staert = "随机选择出生地"
//创建一个选择结果数组
let pools = ["太阳","水星","金星","地球","火星","土星","木星","冥王星"]
//随机选择函数
function random(){
//将数组中的值随机取出
let index = Math.ceil(Math.random()*7)
//取出后写入界面
circle.innerText = pools[index]
//并将按钮中的文字修改
button.innerText = staert
}
</script>
</body>
</html>