jq 弹窗在屏幕随意飘动

jq 让一个弹窗在屏幕中随意飘动,到屏幕边缘就回弹。

效果:

 

 

css:

#box {
width: 100%;
height: 100%;
position: fixed;
border: 1px solid red;
margin: 0;
top: 0;
left: 0;
}

#boll {
width: 50px;
height: 50px;
border-radius: 25px;
background: green;
/*position: absolute;*/
position: fixed;
top: 66px;
left: 88px;
}

 

 

Html:

<div id="box">
<div id="boll"></div>
</div>

 

js:

var box = document.documentElement;
// var box = document.getElementById('box');
var boll = document.getElementById('boll');

//获取屏幕的宽度
var val = box.clientWidth;
//获取屏幕的高度
var two = box.clientHeight;
console.log(two);
//在屏幕的宽度的范围内 取随机数
var sval = parseInt(Math.random() *val);
//在屏幕的高度的范围内 取随机数
var stwo = parseInt(Math.random() *two);
console.log(stwo);

//定义 初始位置
var x = sval,
y = stwo,
timer1 = null,
movex = 1,
movey = 1;
// console.log(box.clientWidth - boll.clientWidth);
// console.log(box.clientWidth - boll.offsetWidth);
//每20毫秒执行
function left() {

//movex==1 x就加 div就会向右移动,每20毫秒移动1px 否则就反之
if(movex) { //判断方向
x++;
if(x >= box.clientWidth - boll.clientWidth){
movex = 0;
}
boll.style.left = x + 'px';
} else {
x--;
if(x <= 0) {
movex = 1;
}
boll.style.left = x + 'px';
}
//movey==1 y就加 div就会向下移动,每20毫秒移动1培训 否则就反之
if(movey){
y++;

if(y >= box.clientHeight - boll.clientHeight) {
movey = 0;
}
boll.style.top = y + 'px';
} else {
y--;
if(y <= 0) {
movey = 1;
}
boll.style.top = y + 'px';
}
}
//hover 时暂停飘动
$("#boll").mouseover(function() {
clearInterval(lun);
});
//离开时,继续飘动
$("#boll").mouseout(function() {
lun = setInterval(left, 20);
});
//每20毫秒执行函数
var lun = setInterval(left, 20);

 

posted @ 2020-05-27 09:09  老和尚106  阅读(278)  评论(0编辑  收藏  举报