“回到顶部”的js代码在谷歌浏览器下为什么不执行?
// JavaScript Document 回到顶部
function goTopEx(){
var obj=document.getElementById("goTopBtn");
function getScrollTop(){
var xtop;
xtop = document.documentElement.scrollTop || document.body.scrollTop;
return xtop;
}
function setScrollTop(value){
if (document.body)
{
document.documentElement.scrollTop=value;
}
else
{
document.documentElement.body=value;
}
}
window.onscroll=function(){getScrollTop()>0?obj.style.display="block":obj.style.display="none";}
obj.onclick=function(){
var gotop;
gotop=window.setInterval(scrollMove,10);
function scrollMove(){
setScrollTop(getScrollTop()/3);
if(getScrollTop()<1)
{
window.clearInterval(gotop);
}
}
alert(gotop);
}
}
在html里我这样调用的,但是在ie,firefox都会执行,在google浏览器里Onclick时没反应!
<DIV style="DISPLAY: none" id=goTopBtn><IMG border=0 src="{res file=images/toTop.png}"></DIV>
<SCRIPT type=text/javascript>goTopEx();</SCRIPT>
[解决办法]
obj.onclick=function(){
var gotop;
gotop=window.setInterval(function(){
setScrollTop(getScrollTop()/3);
if(getScrollTop()<1)
{
window.clearInterval(gotop);
}
},10);
alert(gotop);
}用这个,刚才那个多了一个括号~
[解决办法]
好久没来了,手痒所以写多了,LZ的问题确实是浏览器的兼容性问题
另外: LZ代码里的“document.documentElement.body=value;”是神马?
在chrome 和safari里面获取和设置scrollTop会有点问题,获取的时候只有用pageYOffset才能得到正确的值,设置的时候要用document.body.scrollTop = n,但这两个浏览器又是认document.documentElement的,so...
<!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>
</head>
<body>
<div style="height:1000px;"></div>
<input type="button" id='a' />
<div style="height:200px;"></div>
<script type="text/javascript">
(function(w, n) {
function m(op) {
var step = op.step
[解决办法]
10; //动画的帧频(ms)
var time = op.time
[解决办法]
50; //动画的帧数
var stime = 0;
document.getElementById(op.handle).onclick = function() {
var top = g();
if(top > 0) {
stime = 0;
(function() {
s(Math.ceil(t(stime, top, -top, time)));
if(stime < time) {
stime++;
setTimeout(arguments.callee, step);
}
})();
}
};
}
//缓动算法
function t(t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
}
//获取页面scrollTop
function g() {
//ff / chrome safari / ie
return document.documentElement.scrollTop
[解决办法]
window.pageYOffset
[解决办法]
document.body.scrollTop;
}
//设置页面scrollTop
function s(n) {
//chrome safari / ff / ie
(/(chrome
[解决办法]
version)/i).test(navigator.userAgent)? document.body.scrollTop = n : document.documentElement? document.documentElement.scrollTop = n : document.body.scrollTop = n;
}
w[n] = m;
})(window, 'sbsbbsbs');
//调用
sbsbbsbs({handle: 'a', time: 30});
</script>
</body>
</html>