【碰撞檢測】js實(shí)現(xiàn)元素在頁面中懸浮移動(dòng)。
话不多少,直接上效果图。
贴代码
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>碰撞检测</title>
<style>
html,body{
margin:0;
padding:0;
height:100%;
}
#movele{
position: absolute;
top:0;
left:0;
height:150px;
width:150px;
background-color:red;
border-radius: 50%;
color:#fff;
text-align: center;
}
</style>
</head>
<body>
<div id="movele"><br/><br/><br/>假设这是张图片</div>
</body>
<script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script>
(function(){
var elementMove=function(option){
this.container=option.container;
this.element=option.element;
this.speed = {};
if(option.speed){
if(typeof option.speed=="object"){
this.speed.x = option.speed.x;
this.speed.y = option.speed.y;
}
else{
this.speed.x = option.speed;
this.speed.y = option.speed;
}
}
else{
this.speed.x = 2;
this.speed.y = 2;
}
this.pos={
"left":0,
"top":0
};
this.xdir = 1;
this.ydir = 1;
this.Animation();
};
elementMove.prototype={
move:function(){
this.getPos();
$(this.element).css({
"left":this.pos.left,
"top":this.pos.top
})
this.Animation();
},
getPos:function(){
var jqConTainer = $(this.container);
var jqEle = $(this.element);
var offset = jqEle.offset();
//碰撞检测start
if(offset.left <= 0){
this.xdir = 1;
}
else if(offset.left+jqEle.width() >= jqConTainer.width()){
this.xdir = -1;
};
if(offset.top <= 0){
this.ydir = 1;
}
else if(offset.top +jqEle.height() >= jqConTainer.height()){
this.ydir = -1;
};
//碰撞检测end
this.pos.left = this.pos.left + this.xdir * this.speed.x;
this.pos.top = this.pos.top + this.ydir * this.speed.y;
},
Animation:function(){
var that=this;
requestAnimationFrame(function(){
that.move();
})
},
};
//实例化
var mymoveInstance = new elementMove({
"element" :"#movele",
"container" :"body",
"speed":{
"x":6,
"y":5
}
});
})();
</script>
</html>
这是@懵萌酱 提问的,纯手打一份代码,欢迎交流。
提问原文
點(diǎn)擊查看更多內(nèi)容
5人點(diǎn)贊
評論
評論
共同學(xué)習(xí),寫下你的評論
評論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦