思路:
封装一个获取元素的函数
创建对象
在原型里面写一个随机函
给星星的top,left赋值
调用方法
<!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>
<style>
div {
position: relative;
width:400px;
height:400px;
border:2px solid
}
img {
position: absolute;
}
</style>
</head>
<body>
<div id="div">
<img id="img" src="./Snipaste_2019-03-01_10-48-43.png" alt="">
</div>
<script>
// 封装 获取对象
function $(id) {
return document.getElementById(id);
}
// 创建自定义函数
function ChangeStyle(divobj, imgobj) {
this.divobj = divobj;
this.imgobj = imgobj;
}
// 原型
ChangeStyle.prototype.init = function () {
// 缓存this
var that = this;
// divobj添加点击事件
this.divobj.onclick = function () {
// 随机数
var aa = (function (min, max) {
return Math.floor(Math.random() * (max - min) + min);
})(0, 400);
var bb = (function (min, max) {
return Math.floor(Math.random() * (max - min) + min);
})(0, 400);
that.imgobj.style.top = aa + "px";
that.imgobj.style.left = bb + "px";
}
}
var cs = new ChangeStyle($("div"), $("img"));
cs.init();
</script>
</body>
</html>