function $ (id)
{
return typeof id === "string"?document.getElementById(id):id;
};
window.onload = function ()
{
//获取元素
var oTop = $("to_top");
var timer = null; //定时器变量
var iTop = true;
//鼠标滚动触发
window.onscroll = function (ev)
{
var oEvent = ev || window.event; //坐标
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
//判断滚动条是否大于可视区的高度
if (scrollTop >= document.documentElement.clientHeight)
{
oTop.style.display = "block";
}else
{
oTop.style.display = "none";
}
if (!iTop) //下面 false 时 if 里取反,当if == true 时才会执行
{
clearInterval(timer);
}
iTop = false;
};
oTop.onclick = function ()
{
//设置定时器
timer = setInterval(function ()
{
//获取滚动条到顶部的距离
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
//速度
var iSpeed = Math.ceil(scrollTop / 4);
iTop = true;
//运动
document.documentElement.scrollTop = document.body.scrollTop = scrollTop - iSpeed;
//滚动完成时,关闭定时器
if (scrollTop == 0)
{
clearInterval(timer);
}
},30);
};
};
//这是 js 源码,大家可以拿去参考