思路:
封裝一個獲取元素的函式
建立物件
在原型裡面寫一個隨機函
給星星的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>
複製程式碼