一个网页浮动广告的控制方法

页面需要引用的广告控制代码:
<SCRIPT LANGUAGE="JavaScript">
ads = new Array();
/**
* aTargetLeft 和 aTargetRight 只中必须有一个是-1, 有一个大于-1
*
* aObj - 要作为浮动广告的对象
* aTargetTop - 浮动广告离页面顶部的距离
* aTargetLeft - 如果要让浮动广告靠左,设置此值为广告离页面最左侧的距离,否则设置-1
* aTargetRight - 如果要让浮动广告靠右,设置此值为广告离页面最右侧的距离,否则设置-1
*/
function FlowAD(aObj, aTargetTop, aTargetLeft, aTargetRight){
this.obj = aObj;
this.targetTop = aTargetTop;
this.targetLeft = aTargetLeft;
this.targetRight = aTargetRight;
this.move();
}
FlowAD.prototype.move = function(){
//set the top
var newTop = document.body.scrollTop + this.targetTop;
var maxTop = document.body.scrollHeight - this.obj.style.height.substr(0,this.obj.style.height.length-2);
if(newTop > maxTop){
newTop = maxTop;
}
this.obj.style.top = newTop;

//set the left
if(this.targetLeft > -1){
this.obj.style.left = this.targetLeft + document.body.scrollLeft;
}
if(this.targetRight > -1){
var newLeft = document.body.clientWidth - this.targetRight - this.obj.style.width.substr(0,this.obj.style.height.length-2);
this.obj.style.left = newLeft + document.body.scrollLeft;
}
}
function addAD(aAD){
ads.push(aAD);
}
function moveADs(){
for(var i=0; i<ads.length; i++){
ads[i].move();
}
}
</SCRIPT>


使用方法:
1. 把以上控制广告的js代码引用到页面里。
2. 在页面上任何地方(当然要在body里边)加上广告元素,例如:
<div id="ad1" style="width:100px; height:180px; position:absolute; background-color:red">asdfa</div>
<div id="ad2" style="width:100px; height:180px; position:absolute; background-color:red">asdfaf</div>
其中下边的字段是必须设置的:id 和 style里的width,height,position:absolute。这里设置为红色只是为了让广告看起来明显。
3. 添加广告的初始化函数,例如initADs,在函数initADs 中加入要设置为浮动的广告,可以参照下边的例子
	function initADs(){
//举例添加两个广告,离顶部200。第一个靠左,距离左边2;第二个靠右,距离右边2
addAD(new FlowAD(window.ad1, 200, 2, -1));
addAD(new FlowAD(window.ad2, 200, -1, 2));
}

4. 必须设置window.onresize和window.onscroll事件为moveADs,并且保证在页面载入之后能调用initADs,例如使用下边方法:
<SCRIPT LANGUAGE="JavaScript">
window.onload = initADs;
window.onresize = moveADs;
window.onscroll = moveADs;
</SCRIPT>


//欢迎批评,建议,请致E-mail: zyongsheng83@163.com
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值