admin管理员组

文章数量:1356854

I'm trying to imitate scrollTop (jQuery) in vanilla JS, so on click it scrolls to an element. This works fine - unless you have already scrolled past the element. So it doesn't scroll the opposite way. Should my formula incorporate window.pageYOffset?

var moves = function(scrollz) {
    var scrollPos = document.getElementById(scrollz).offsetTop - ((document.documentElement.clientHeight - document.getElementById(scrollz).offsetHeight) / 2);

    var timerID = setInterval(function() {
        window.scrollBy(0, speed);
        if (window.pageYOffset >= scrollPos) {
            clearInterval(timerID);
        }
    }, 13);
}

I'm trying to imitate scrollTop (jQuery) in vanilla JS, so on click it scrolls to an element. This works fine - unless you have already scrolled past the element. So it doesn't scroll the opposite way. Should my formula incorporate window.pageYOffset?

var moves = function(scrollz) {
    var scrollPos = document.getElementById(scrollz).offsetTop - ((document.documentElement.clientHeight - document.getElementById(scrollz).offsetHeight) / 2);

    var timerID = setInterval(function() {
        window.scrollBy(0, speed);
        if (window.pageYOffset >= scrollPos) {
            clearInterval(timerID);
        }
    }, 13);
}
Share Improve this question edited Nov 16, 2014 at 3:20 Weafs.py 23k9 gold badges57 silver badges79 bronze badges asked Jan 18, 2013 at 18:21 NeoNeo 1,0373 gold badges12 silver badges30 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 4

scrollBy will scroll from "actual position" to "number of pixel defined" I think you might take a look at scrollTo

本文标签: How to scroll to the top using vanilla JavaScriptStack Overflow