Cross browser JavaScript (not jQuery…) scroll to top animation

后端 未结 20 1054
抹茶落季
抹茶落季 2020-11-22 11:01

I\'m looking for a simple, cross-browser \"scroll to top\" animation I can apply to a link. I don\'t want to require a JS library such as jQuery/Moo, etc.

//         


        
20条回答
  •  遥遥无期
    2020-11-22 11:34

    Linear scrolling animation to bottom. Pure JS, no JQuery. Maybe my solution will be helpful for someone.

    let action_count = 8;
    let speed_ms = 15;
    let objDiv = document.getElementsByClassName('js_y5_area3').item(0);
    
    let scroll_height = objDiv.scrollHeight;
    let window_height = objDiv.offsetHeight;
    
    let scroll_top = objDiv.scrollTop;
    let need_scroll_top = scroll_height - window_height;
    
    if (scroll_top < need_scroll_top)
    {
        let step = Math.ceil((need_scroll_top - scroll_top) / action_count);
    
        let scrollInterval = setInterval(function()
        {
            scroll_top += step;
            objDiv.scrollTop = scroll_top;
    
            if (scroll_top >= need_scroll_top)
            {
                clearInterval(scrollInterval);
            }
    
        }, speed_ms);
    }
    

    You can change variables action_count, speed_ms to configure scrolling animation on your taste.

提交回复
热议问题