使用javascript平滑滚动

时间:2017-04-30 18:40:42

标签: javascript scroll

我写的这个工作正常。它跳到顶部,但我希望它是一个平滑的滚动。如果没有JQuery,我怎样才能实现这一目标?

document.querySelector('.scrolltop').addEventListener('click', footerScroll)

function footerScroll(){
   console.log("clicked");
   window.scrollTo(0, 0);
};

感谢。

1 个答案:

答案 0 :(得分:0)

试试这个:

        (function(){
        var color= 'red';
        var fhwScrollerDiv = document.createElement('div');
        fhwScrollerDiv.innerHTML='<svg width="50" height="50" viewbox="0 0 100 100"><circle  fill="'+color+'" cx="50" cy="50" r="50" /><path stroke="white" stroke-width="16" stroke-linecap="round" d="M50 80 L50 20 M50 20 L80 50 M50 20 L20 50"/></svg>';
        fhwScrollerDiv.style.cssText='z-index:1000;position:fixed;bottom:10px;right:10px;cursor:pointer;display:none;transition:all 0.5s;';
        document.body.appendChild(fhwScrollerDiv);
        var _=fhwScrollerDiv.style;
        window.onscroll = function() {
            if (this.pageYOffset > 200) {
                _.opacity = "0.5";
                _.display = "block";
            } else {
                _.opacity = "0";
                _.display = "none";
            }
        };
        fhwScrollerDiv.onmouseover = function() {
          _.opacity = "1";
        };
        fhwScrollerDiv.onmouseout = function() {
          _.opacity = "0.5";
        };
        var scrollen = function(){
            var scrollDuration = 500,
            scrollHeight = window.pageYOffset,
            scrollStep =  scrollDuration / 15 , 
            scrollCount = 0,
            scrollInterval = setInterval( function() {
                if ( window.pageYOffset != 0 ) {
                    scrollCount = scrollCount + 1;  
                    window.scrollTo( 0, ( scrollHeight-scrollCount*scrollStep) );
                } 
                else clearInterval(scrollInterval); 
                },15 );

        }
        fhwScrollerDiv.onclick = scrollen;  
        fhwScrollerDiv.addEventListener('touchstart', function(){
            event.preventDefault();
            scrollen();
        });
        })();

js fiddle