Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

javascript - document.body.scrollTop Firefox returns 0 : ONLY JS

Any alternatives in pure javascript?

The following works in opera, chrome and safari. Have not tested yet on explorer:

http://monkey-me.herokuapp.com

https://github.com/coolcatDev/monkey-me-heroku/blob/master/static/js/myscripts.js

At page load should scroll down to div '.content':

var destiny = document.getElementsByClassName('content');
var destinyY = destiny[0].offsetTop;
scrollTo(document.body, destinyY, 200);

function scrollTo(element, to, duration) {
    if (duration <= 0) return;
    var difference = to - element.scrollTop;
    var perTick = difference / duration * 2;

    setTimeout(function() {
        element.scrollTop = element.scrollTop + perTick;
        scrollTo(element, to, duration - 2);
    }, 10);
};
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try using this: document.documentElement.scrollTop. If I am correct document.body.scrollTop is deprecated.

Update

Seems like Chrome does not play along with the answer, to be safe use as suggested by @Nikolai Mavrenkov in the comments:

window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0

Now all browsers should be covered.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...