js實現廣告漂浮效果 – Javascript教程_JS教程_技術文章 – 程式設計聯盟

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title></title>
<style type="text/css">
p{
position:absolute;
}
</style>
</head>
<body>
<p id="floatp">
<img src="1.jpg" height="100px" width="200px">

</p>
</body>
</html>
<script language="javascript" type="text/javascript">
/*
利用window對象,實現浮動效果

 1、有一個p,就是我們要控制的,它的起始點坐標(0,0)
 2、設定橫向和縱向的速度
 3、控制p移動
  1)p是否到達邊界,設置圖片速度反向移動
*/
//獲取圖片所在的p對象www.aiwalls.com
 
var img=document.getElementById("floatp");
//設置p起始點坐標
var x=0,y=0;
//設置p行進速度
var xSpeed=2,ySpeed=1;
//設置圖片移動
var w=document.body.clientWidth-200,h=document.body.clientHeight-100;
function floatp(){
 //比較圖片是否到達邊界,如查到達邊界 改變方向;如未到達邊界
 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("floatp()",10);
}
floatp();
</script>

摘自 youngerhao的專欄

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *