JavaScript实现屏保弹弹弹效果
<!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>
.circle{
width: 100px;
height: 100px;
background:red;
border-radius: 50%;
position: fixed;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="circle"></div>
<script>
function Circle(){
this.width = 100;
this.height = 100;
this.dom = document.querySelector('.circle');
this.__left = 0;
this.__top = 0;
this.xDis = 2;
this.yDis = 2;
Object.defineProperty(this,'left',{
get:function(){
return this.__left;
},
set:function(val){
if(val < 0){
this.xDis = -this.xDis;
val = 0;
} else if(val > document.documentElement.clientWidth - this.width) {
val = document.documentElement.clientWidth - this.width;
this.xDis = -this.xDis;
}
this.__left = val;
this.dom.style.left = val + 'px';
}
});
Object.defineProperty(this,'top',{
get:function(){
return this.__top;
},
set:function(val){
if(val < 0){
this.yDis = -this.yDis;
val = 0;
} else if(val > document.documentElement.clientHeight - this.height) {
val = document.documentElement.clientHeight - this.height;
this.yDis = -this.yDis;
}
this.__top = val;
this.dom.style.top = val + 'px';
}
});
}
var circle = new Circle();
function animation(){
circle.left += circle.xDis;
circle.top += circle.yDis;
requestAnimationFrame(animation);
}
animation()
</script>
</body>
</html>