javascript实现div跟随滚动条移动
实现过程中遇到的主要问题有两点
首先要解决的是在不同浏览器下获取ScrollTop值的问题,采取的方法是:
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop||0;
需要注意的是在HTML文件首部要包含DTD声明:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
接着是window.setInterval();函数体要放在setInterval中,否则firefox及chrome浏览器下执行会有问题;
最终的代码为:
window.setInterval(function moveWithScroll() { var scrollDiv=document.getElementById('scrollDiv'); var w=document.documentElement.clientWidth; var h=document.documentElement.clientHeight; var ow=scrollDiv.style.width; var oh=scrollDiv.style.height; var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop||0; var nowW=(w-parseInt(ow))/2; var nowH=(scrollTop+h-parseInt(oh))-400/2; scrollDiv.style.left=nowW+"px"; scrollDiv.style.top=nowH+"px"; },50);
scrollDiv为要滚动的div的ID
相关推荐
letheashura 2020-05-10
hgzhang 2019-12-05
JavaJspSsh 2019-11-18
骷髅狗 2019-11-04
zengni 2019-11-02
dly 2015-05-29
jluzh00 2019-09-08
hanfox 2019-05-29
dengjianbin 2018-08-24
luckylqh 2019-04-13
gjcxywwx 2019-07-01
ajhongshaorou 2019-06-29
81497307 2018-08-24
Burgdan 2017-03-19
CoreyJia 2017-03-14
JessieJWang 2019-06-28
84483065 2016-03-08