1. 程式人生 > >js原生實現網頁廣告條飛舞的效果

js原生實現網頁廣告條飛舞的效果

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title></title>
<style type="text/css">
div{
position:absolute;
}
</style>
</head>
<body>
<div id="floatdiv">
<img src="1.jpg" height="100px" width="200px">
</
div> </body> </html> <script language="javascript" type="text/javascript"> /* 利用window物件,實現浮動效果 1、有一個div,就是我們要控制的,它的起始點座標(0,0) 2、設定橫向和縱向的速度 3、控制div移動 1)div是否到達邊界,設定圖片速度反向移動 */ //獲取圖片所在的div物件 var img=document.getElementById("floatdiv"); //設定div起始點座標 var x=0,y=0; //設定div行進速度 var xSpeed=2,ySpeed
=1; //設定圖片移動
//要是高度獲取不到,h=document.documentElement.clientHeight; var w=document.body.clientWidth-200,
h
=document.body.clientHeight-100;
function floatdiv(){ //比較圖片是否到達邊界,如查到達邊界 改變方向;如未到達邊界 if(x>w||x<0) xSpeed= -xSpeed; if(y>h||y<0) ySpeed= -ySpeed; x+=xSpeed; y+=ySpeed; //設定座標值,起始座標+速度 img.style.top
=y+"px"; img.style.left=x+"px"; setTimeout("floatdiv()",10); } floatdiv(); </script>