最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to scroll to the top using vanilla JavaScript? - Stack Overflow

programmeradmin3浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论