效果图如下:
效果说明:
刷新页面时,广告窗默认按指定方向进行移动,在碰到浏览器边缘的时候,向相反的方法继续运动,当鼠标移动到广告窗上时,广告窗停止运动,当鼠标移开时,广告窗继续运动。在点击关闭按钮后,广告窗隐藏,1s后广告窗再次出现,第四次点击关闭的时候,广告窗彻底隐藏。
代码如下:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>移动的广告</title>
</head>
<style>
#guangg {
position: fixed;
left: 0;
top: 0;
width: 300px;
height: 150px;
border: 1px solid #BEBEBE;
background: pink;
}
#close {
width: 300px;
height: 30px;
text-align: center;
line-height: 30px;
color: #f46e00;
background: #BEBEBE;
box-shadow: 0 0 2px rebeccapurple;
}
#close > span {
position: absolute;
right: 0;
top: 0;
width: 30px;
height: 30px;
color: white;
text-align: center;
background: #cccccc;
user-select: none;
}
#txt {
padding-top: 20px;
}
</style>
<body>
<div id="guangg">
<div id="close">
温馨提示
<span>X</span>
</div>
<div id="txt">
文本展示
<p>说明:点击第四次关闭时,不再出现</p>
</div>
</div>
<script type="text/javascript">
let gg = document.getElementById('guangg'); // 抓取广告框
let close = document.getElementById('close'); // 抓取关闭按钮
let boxHeight = gg.clientHeight, boxWidth = gg.clientWidth; // 获取广告框的宽度和高度
let vw = window.innerWidth, vh = window.innerHeight; // 可视窗口大小
let mx = 1, my = 1; // 每次移动的像素
let mw = 0, mh = 0; // 移动总量
let num = 0; // 点击关闭次数
let maxNum = 3; // 关闭几次后消失
let interval = 0; // 定时器个数
let time = 10; // 定时器时间(运动时)
let closeTime = 1000; // 定时器时间(关闭时)
/*
* 广告窗移动
*
* */
function autoPlay_gg() {
interval = 0;
interval = setInterval(function () {
mw = mw + mx;
mh = mh + my;
if (mw >= vw - boxWidth || mw <= 0) {
mx = -1 * mx;
}
if (mh >= vh - boxHeight || mh <= 0) {
my = -1 * my;
}
gg.style.left = mw + 'px';
gg.style.top = mh + 'px';
}, time);
}
autoPlay_gg();
/*
* 鼠标移动到广告窗上时,暂停移动
*
* */
gg.onmousemove = function () {
clearInterval(interval); // 清除定时器
};
gg.onmouseleave = function () {
clearInterval(interval);
autoPlay_gg(); // 广告窗运动
};
/*
* 点击关闭按钮时
*
* */
close.onclick = function () {
gg.style.display = 'none'; // 隐藏广告窗
num++;
if (num <= maxNum) {
setTimeout(function () {
gg.style.display = 'block'; // 显示广告窗
}, closeTime)
} else {
gg.parentNode.removeChild(gg); // 删除广告窗
}
}
</script>
</body>
</html>