js每天一练习09-16

回到顶部,还是有一些问题,希望高手指教!

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
body{ height:3000px;}
#huiTop{ width:80px; height:80px; background:#CCC; color:#333; line-height:80px; text-align:center; border:solid 1px #999; position:absolute; bottom:0px; right:0px;}
</style>
</head>

<body>
<div id="huiTop">回到顶部</div>
<script>
var oTop=document.getElementById("huiTop");//获取对象oTop
var scrtop=document.documentElement.scrollTop||document.body.scrollTop;// 预定值,获取上面卷入的高,documentElement兼容IE,body兼容谷歌
oTop.onclick=function()
{

startMove(oTop,{bottom:"0"});
window.scrollTo(0,0)
}

window.onscroll=window.onresize=function ()
{
var oTop=document.getElementById("huiTop");//获取对象oTop
var scrtop=document.documentElement.scrollTop||document.body.scrollTop;// 预定值,获取上面卷入的高,documentElement兼容IE,body兼容谷歌
scrtop=-scrtop;
console.log(scrtop);
startMove(oTop,{bottom:scrtop});//调用运动涵数,{对象,{属性,值},涵数}

}

function getStyle(obj, name)//获非行间样式涵数
{
if(obj.currentStyle)//当浏览器支持时,用currentStyle获取值
{
return obj.currentStyle[name];
}
else
{
return getComputedStyle(obj, false)[name];//不支持获值.
}
}


//startMove(oDiv, {width: 400, height: 400})


function startMove(obj, json, fnEnd)
{
clearInterval(obj.timer);//取消定时器
obj.timer=setInterval(function (){//设置定时器
var bStop=true; //假设:所有值都已经到了

for(var attr in json)//循环改变属性
{
var cur=0;//改变属性差距

if(attr=='opacity')//如果是透明度
{
cur=Math.round(parseFloat(getStyle(obj, attr))*100);//cur赋值当前透明度,getStyle获取透明度值,乘以100,parseFloat返回小数点,round四舍五入
}
else
{
cur=parseInt(getStyle(obj, attr));//cur赋值当前值
}

var speed=(json[attr]-cur)/6;
//console.log(json[attr]);设置速度
speed=speed>0?Math.ceil(speed):Math.floor(speed);//大于0向上舍,小于0向下舍

if(cur!=json[attr])//当前值不等于预定值,向下执行下面涵数
bStop=false;

if(attr=='opacity')
{
obj.style.filter='alpha(opacity:'+(cur+speed)+')';//透明度执行动做
obj.style.opacity=(cur+speed)/100;
}
else
{
obj.style[attr]=cur+speed+'px';//其它动执行效果
}
}

if(bStop)//当前值等于预定值,取消定时器
{
clearInterval(obj.timer);

if(fnEnd)fnEnd();
}
}, 30);
}

</script>
</body>
</html>

posted @ 2014-09-16 22:42  随波逐流196  阅读(53)  评论(0)    收藏  举报