js 实现网页图片随滚动条移动
经常在sina网页上看到一个浮动窗口随着滚动条移动,觉得很好玩,于是自己就抽空实现了一个。代码如下:
var imgTopMargin = -40;
var imgSpeed = 15;
var timeSpeed = 200;
var hLimit = 0;
var timer;
function checkImg()
{
var reTimer = timeSpeed;
if(document.body.offsetHeight > hLimit)
{
var startPoint = parseInt(document.all.sImg.style.top,10);
var endPoint = document.body.scrollTop;
endPoint = (imgTopMargin <= endPoint ) ? endPoint - imgTopMargin : 0;
if(startPoint != endPoint)
{
moveAmount = Math.ceil(Math.abs(endPoint - startPoint) / 15);
document.all.sImg.style.top = parseInt(document.all.sImg.style.top,10) + ((endPoint<startPoint) ? -moveAmount : moveAmount);
reTimer = imgSpeed;
}
}
else
{
document.all.sImg.style.top = 0;
}
timer=setTimeout("checkImg();",reTimer);
}
function initImg()
{
document.all.sImg.style.top = document.body.scrollTop;
checkImg();
}
注意:
1.红色字体是我在页面中div或者图片的id
2.如果网页的头部是<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">请把代码中的document.body.scrollTop改成document.documentElement.scrollTop,否则scrollTop取值总为0,具体原因不清楚。