js之广告
2018-06-24 02:09:18来源:未知 阅读 ()
涉及到offset等有关获取各种尺寸问题下
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>广告</title>
<style>
*{
padding: 0;
margin: 0;
}
#ad{
width: 300px;
height: 200px;
background: url(images/400.jpg) no-repeat;
position: absolute;
left: 0;
top: 0;
}
#close{
width: 20px;
height: 20px;
}
</style>
</head>
<script type="text/javascript">
window.onload = function(){
var ad= document.getElementById("ad");
var close = document.getElementById("close");
// 获得可视区域的宽高
var win_height = document.documentElement.clientHeight;
var win_width = document.documentElement.clientWidth;
// 计算可以到达的最大top和left值
var max_top = win_height - ad.offsetHeight;//屏幕高度减去图片高度
var max_left = win_width - ad.offsetWidth;
var x = 2;y = 5;//xy均为移动速度
//设置函数控制怎么移动
function run(){
// 获得旧的left和top
var old_left = ad.offsetLeft;
var old_top = ad.offsetTop;
// 计算新的
var new_left = old_left + x;//加上移动速度x,y
var new_top = old_top + y;
// 需要判断超出,控制速度及其方向
if (new_top>max_top) {//加速到屏幕边沿时,设置new_top = max_top;即速度为0就停下
new_top = max_top;
}
if (new_left>max_left) {
new_left = max_left;
}
if (new_left<0) {
new_left = 0
}
if (new_top<0) {
new_top = 0
}
// 赋值
ad.style.left = new_left + 'px';
ad.style.top = new_top + 'px';
//当new_top = max_top;即速度为0,此时速度设为相反方向即可
if (new_top == max_top) {
y = -2;
}
if (new_top == 0) {
y = 2;
}
if (new_left == max_left) {
x = -2;
}
if (new_left == 0) {
x = 2;
}
}
// 设置定时器,每隔一段时间就改变一下left top
var timer = setInterval(run,3);
// 定时器结束
//给ad加鼠标移入事件
ad.onmouseover = function(){
// 停止定时器
clearInterval(timer)
};
// 给ad加鼠标移出事件
ad.onmouseout = function(){
//重启定时器
timer = setInterval(run,3)
};
//点击关闭广告
close.onclick = function(){
ad.style.display = 'none';
};
// 窗口改变事件
window.onresize = function(){//window.onresize = function(){....}浏览器尺寸变化响应事件
//广告归位
//重新将广告放到左上角
ad.style.left = 0;
ad.style.top = 0;
// 将他的速度重新定义
x = 2;
y = 5;
// 重新获得可视区域的宽高
win_height = document.documentElement.clientHeight;
win_width = document.documentElement.clientWidth;
// 重新计算可以到达的最大top和left值
max_top = win_height - ad.offsetHeight;
max_left = win_width - ad.offsetWidth;
}
}
</script>
<body>
<div id="ad">
<img src="images/X.jpg" id="close">
</div>
</body>
</html>
次总结
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- jQuery如何动态添加小广告 2020-02-20
- 网站广告“加速”显示的方法 2019-09-30
- js实现简单进度条 2019-08-14
- 移动网页广告引入mraid.js使用指南 2019-02-27
- 广告代码教你不影响网页加载速度的步骤 2018-12-25
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash
