js實現圖片浮動
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>js實現圖片輪播</title>
<style type="text/css">
#main{width:1024px; margin:20px auto;text-align:center;}
#adv{width:200px;height:400px;position:absolute;top:10px;left:20px;}
a {border:1px solid gray;background-color:green; position:absolute;top:0px;left:150px;color:grap;}
</style>
<script type="text/javascript">
var localX;
var localY;
//預載入 js的執行順序是自上而下的,所以要用預載入
onload = function()
{
var adv = $("#adv");
//adv.style.top adv.style.left 只能取到行內的樣式
localX = document.defaultView.getComputedStyle(adv,null).left; //可以取到所有的樣式
localY = document.defaultView.getComputedStyle(adv,null).top;
}
//新增滾動事件
onscroll = function()
{
//取到滾動距頂部的距離 採用容錯處理 ,2中方法
var scrollX = document.documentElement.scrollLeft ? document.documentElement.scrollLeft:
document.body.scrollLeft;
var scrollY = document.documentElement.scrollTop ? document.documentElement.scrollTop:
document.body.scrollTop;
//要浮動的圖片的距離
$("#adv").style.left = scrollX +parseInt(localX)+"px";
$("#adv").style.top = scrollY +parseInt(localY)+"px";
}
//關閉浮動廣告的函式
function colseAdv()
{
document.body.removeChild($("#adv"));
return false;
}
//通過getElement物件的方法進行封裝
//要求:id使用#字首 class使用.字首 標籤不用
function $(name)
{
if(name.charAt(0) == '#')
{
return document.getElementById(name.substring(1));
}
else if(name.charAt(0) == '.')
{
return document.getElementsByClassName(name.substring(1));
}
else
{
return document.getElementsByTagName(name);
}
}
</script>
</head>
<body>
<div id = 'main'>
<img src= '../images/top.jpg' />
<img src= '../images/content1.jpg' />
<img src= '../images/content2.jpg' />
<img src ='../images/foot.jpg' />
</div>
<div id = 'adv'>
<!-- 要浮動的圖片 -->
<img src="../images/left.jpg"/>
<a href = "#" onclick = "return colseAdv()">關閉</a>
</div>
</body>
</html>