// 页面结构
<div id="FloatDiv"></div>
// 样式
position: absolute;
z-index: 1;
width: 50px;
height: 50px;
background-color:
}
// 方法
startFloat () {
let FloatDiv = document.getElementById('FloatDiv')
FloatDiv.visibility = "visible"
let xPos = 400
let yPos = 300
let height = 0
let Hoffset = 0
let Woffset = 0
let yon = 0
let xon = 0
function move() {
let width = document.documentElement.clientWidth;
height = document.documentElement.clientHeight;
Hoffset = FloatDiv.offsetHeight;
Woffset = FloatDiv.offsetWidth;
FloatDiv.style.left = (xPos + document.body.scrollLeft + document.documentElement.scrollLeft) + "px";
FloatDiv.style.top = (yPos + document.body.scrollTop + document.documentElement.scrollTop) + "px";
if (yon) {
yPos = yPos + 1;
} else {
yPos = yPos - 1;
}
if (yPos < 0) {
yon = 1;
yPos = 0;
}
if (yPos >= (height - Hoffset)) {
yon = 0;
yPos = (height - Hoffset);
}
if (xon) {
xPos = xPos + 1;
} else {
xPos = xPos - 1;
}
if (xPos < 0) {
xon = 1;
xPos = 0;
}
if (xPos >= (width - Woffset)) {
xon = 0;
xPos = (width - Woffset);
}
}
this.timer = setInterval(move, 40);
let that = this
FloatDiv.onmouseover = function () {
clearInterval(that.timer);
}
FloatDiv.onmouseout = function () {
that.timer = setInterval(move, 40);
}
},
// 渲染完DOM后调用
this.startFloat()