這個浮動效果蠻有趣的,程式碼不多,特別分享給大家:
複製程式碼 程式碼如下:
<html>
<head>隨機浮動
<style type="text/css">
#divimg{
/*
對圖片進行絕對定位
*/
position:absolute;
}
</style>
</head>
<body>
<div id="divimg">
<img src="../../resource/images/float.jpg" width="205" height="108">
</div>
<script language="javascript" type="text/javascript">
//獲取圖片的所有 div 對象
var divimg=document.getElementById("divimg");
//設置起始位置
var x=0,y=0;
//設置圖片的前進速度
var xSpeed=8,ySpeed=2;
//設置圖片浮動高度和寬度
var w=document.documentElement.clientWidth-205,h=document.body.clientHeight-108;
function floatimg(){
//比較是否達到邊界,如果達到邊界以後就改變圖片的方向為反向,如果未達到邊界則繼續向前
if(x<0||x>w) xSpeed=-xSpeed;
if(y<0||y>h) ySpeed=-ySpeed;
x+=xSpeed;
y+=ySpeed;
setTimeout("floatimg()",1000);
var n=divimg.style.top=Math.round(Math.random()*h)+"px";
var m=divimg.style.left=Math.round(Math.random()*w)+"px";
}
floatimg();
</script>
</body>
</html>
這裡用絕對定位讓圖片脫離文件流,再用 xSpeed、ySpeed 控制移動方向與速度,並透過 setTimeout 週期性呼叫 floatimg,同時用 Math.random 隨機決定圖片在視窗範圍內的位置,達到不定向飄動的效果。