js浮动广告
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
*{ padding:0; margin:0;}
body{ width:100%; height:2000px;}
#myDiv{ width:200px; height:200px; background-color:#f00; position:absolute; top:0; left:0;}
</style>
<script type="text/javascript">
window.onload=function(){
var myDiv = document.getElementById("myDiv");
var elemWidth = myDiv.offsetWidth;
var elemHeight = myDiv.offsetHeight;
var clientW = clientWidth();
var clientH = clientHeight();
moveElement(myDiv,0,clientW,0,clientH,10,1,2,elemWidth,elemHeight);
//滚动条滚动时间触发
window.onscroll=function(){
var scrollTop = getScrollTop();
top_y=scrollTop;
bottom_y=top_y+clientH;
moveElement(myDiv,0,clientW,top_y,bottom_y,10,1,2,elemWidth,elemHeight)
};
};
//控制小方块的移动
function moveElement(elem,left_x,right_x,top_y,bottom_y,interval,dx,dy,elemWidth,elemHeight){
if(elem.moveMent){
clearTimeout(elem.moveMent);
}
var xpos = getCssStyle(elem,"left");
var ypos = getCssStyle(elem,"top");
if(xpos>right_x-elemWidth){
dx=-Math.abs(dx);
}
if(xpos<left_x){
dx=Math.abs(dx);
}
if(ypos<top_y){
dy=Math.abs(dy);
}
if(ypos>bottom_y-elemHeight){
dy=-Math.abs(dy);
}
xpos+=dx;
ypos+=dy;
elem.style.left=xpos+"px";
elem.style.top=ypos+"px";
elem.moveMent=setTimeout(function(){moveElement(elem,left_x,right_x,top_y,bottom_y,interval,dx,dy,elemWidth,elemHeight);},interval);
}
//取得elem元素的property样式
function getCssStyle(elem,property){
var computedStyle="";
if(elem.currentStyle){
computedStyle=elem.currentStyle[property];
}else if(document.defaultView.getComputedStyle){
computedStyle=document.defaultView.getComputedStyle(elem,null)[property];
}
return parseInt(computedStyle);
}
//浏览器视口的宽度
function clientWidth(){
var clientW = Math.min(document.documentElement.clientWidth,document.documentElement.scrollWidth);
return clientW;
}
//浏览器视口的高度
function clientHeight(){
var clientH = Math.min(document.documentElement.clientHeight,document.documentElement.scrollHeight);
return clientH;
}
//文档的高度
function scrollHeight(){
var scrollH = Math.max(document.documentElement.clientHeight,document.documentElement.scrollHeight);
return scrollH;
}
//文档的宽度
function scrollWidth(){
var scrollW = Math.max(document.documentElement.clientWidth,document.documentElement.scrollWidth);
return scrollW;
}
//取得文档上部被卷去的部分
function getScrollTop(){
var scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
return scrollTop;
}
</script>
</head>
<body>
<div id="myDiv"></div>
</body>
</html>
容易出错的地方是:控制小方块移动的那块代码判断的时候一定要加math.abs(); 因为如果不加的话如果速度过快,小方块会一直卡在视口的边缘,颤动,因为dy=-dy;小方块会向上执行dy距离向下移动dy距离,永远不会有实际上的超过dy距离上下浮动的范围。
浙公网安备 33010602011771号