<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>js飘窗</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#promptBox {
position: fixed;
width: 30%;
height: 30%;
z-index: 999;
background-color: cornflowerblue;
padding:5px;
}
#guanBi{
text-align: right;
}
</style>
</head>
<body>
<div id="promptBox">
<div id="prompt">
<div id="guanBi">
<div>
X
</div>
</div>
<div>
我是一个飘窗······
</div>
</div>
</div>
<div style="width: 2000px;height:1000px;background-color: rgb(223, 89, 56);">
</div>
<script src="./jquery.js"></script>
<script type="text/javascript">
var div = document.getElementById("promptBox");//获取对象
var myt = 50, myl = 0; //定义初始top/left值
var step = 10; //要移动多少像素 影响快慢
var w = div.offsetWidth, h = div.offsetHeight;//获取元素的宽高
console.log(w)
console.log(h)
var bw = window.innerWidth, bh = window.innerHeight;//获取浏览器可见窗口的宽高
console.log(bw)
console.log(bh)
var directionX = "right", directionY = "down";//定义移动方向
function go() {
//判断移动方向
if (directionX == "right") {//判断向右移动时到最右侧
if ((myl + w + step) > bw) {
directionX = "left";
}
} else {
if ((myl - step) < 0) {
directionX = "right";
}
}
if (directionY == "down") {//判断向下移动时到最下侧
if ((myt + h + step) > bh) {
directionY = "up";
}
} else {
if ((myt - step) < 0) {
directionY = "down";
}
}
//移动
if (directionX == "right") {
myl += step;
} else {
myl -= step;
}
if (directionY == "down") {
myt += step;
} else {
myt -= step;
}
div.style.left = myl + "px";
div.style.top = myt + "px";
}
var myVar = setInterval(go, 40);//定时器
div.onmouseover = function () {//鼠标移动到元素上停止函数
clearInterval(myVar);
}
div.onmouseout = function () {//鼠标离开元素继续
myVar = setInterval(go, 40);
}
</script>
<script>
// 点击关闭事件
var none = document.getElementById("guanBi");
none.onclick = function () {
$("#promptBox").fadeOut();
}
</script>
</body>
</html>