使用js完成一个类似于小广告的功能,斜着运动,遇到边界弹回

不多说先上效果图:

使用js完成一个类似于小广告的功能,斜着运动,遇到边界弹回


如何实实现上面的效果呢,代码如下:

html部分:

         <!--   html部分定义个几个div盒子    -->

<!--   这里是一个显示mobile的div -->
<div class="mobileDiv" style="display:block;">
<a href="mailto:[email protected]">
<div class="mobileCooperateDialog floatDiv">
<span>合作垂询</span>
</div>
</a>

<div class="mobileleaveMsgDialog floatDiv" onclick="window.location.href='${(site.siteUrl)!}/lxwm/givemsg/index.html'"  >
<span>留言我们</span>
</div>
<div class="mobilesaleLine floatDiv">
<span>销售热线 010-6588718</span>
</div>
<div class="mobilecomplain floatDiv" onclick="window.location.href='${(site.siteUrl)!}/lxwm/complain/index.html'">
<span>投诉建议</span>
</div>
  
  </div>


css部分:

 <style>
/*
  这段div是用来定义手机运动的四个框的
*/
.floatDiv{
position:fixed;
width:100px;
height:60px;
background-color:yellow;
}
.mobileCooperateDialog{
top:0px;
left:0px;
}
.mobileleaveMsgDialog{
top:0px;
right:0px;
}
.mobilesaleLine{
bottom:0px;
left:0px;
}
.mobilecomplain{
bottom:0px;
right:0px;
}
</style>

重点在javascript代码:




<script language="javascript">

        //获取浏览器屏幕的宽和高
var screenWidth = document.documentElement.clientWidth;
var screenHeight = document.documentElement.clientHeight;

       /*

       MoveableDiv这个是定义好的一个js对象

       传入参数的含义如下:

name: 名称,没有也可以

                 jQueryObject:传入进来一个jQuery对象,代表了某个div盒子

                 x_location:距离浏览器左上方顶点的绝对定位x坐标

                 y_location:距离浏览器左上方顶点的绝对定位y坐标

                 xSpeed:x方向上的初始速度

                 ySpeed:y方向上的初始速度

      */
function MoveableDiv(name,jQueryObject,x_location,y_location,xSpeed,ySpeed){
this.name = name;
this.jQueryObject = jQueryObject;
this.x_location = x_location;
this.y_location = y_location;
this.xSpeed = xSpeed;
this.ySpeed = ySpeed;
}

MoveableDiv.prototype = {
constructor: MoveableDiv,

                //下面的move方法定义的是盒子的运动,当触碰到边界的时候将速度方向相反即可
move:function(){
if( this.x_location>(screenWidth-$(this.jQueryObject).width()) || this.x_location<0 ){
this.xSpeed = -this.xSpeed;
}
if( this.y_location>(screenHeight-$(this.jQueryObject).height()) || this.y_location<0 ){
this.ySpeed = -this.ySpeed;
}
this.x_location+=this.xSpeed;
this.y_location+=this.ySpeed;
$(this.jQueryObject).css("left",this.x_location+"px");
$(this.jQueryObject).css("top",this.y_location+"px");
}
}

$(function(){
//新建四个对象,初始化赋值
var movediv1 = new MoveableDiv("movediv1",$('.mobileCooperateDialog'),0,0,5,5);
var movediv2 = new MoveableDiv("movediv1",$('.mobileleaveMsgDialog'),screenWidth-$(".mobileleaveMsgDialog").width(),0,5,5);
var movediv3 = new MoveableDiv("movediv1",$('.mobilesaleLine'),0,screenHeight-$(".mobilesaleLine").height(),5,5);
var movediv4 = new MoveableDiv("movediv1",$('.mobilecomplain'),screenWidth-$(".mobilecomplain").width(),screenHeight-$(".mobilecomplain").height(),5,5);

//设置一个定时器,让其运动
setInterval(function(){
movediv1.move();
movediv2.move();
movediv3.move();
movediv4.move();
},50)

})

</script>