简体   繁体   English

使用纯 JAVASCRIPT 滚动到网站的顶部链接(jquery)

[英]Scroll to top link for website using pure JAVASCRIPT without(jquery)

I want normal scroll to top for website.我想要网站的正常滚动到顶部。

The scroll to top link appears at the bottom of page(near footer) which only visible after 200px mouse scroll down and should be hidden when scroll back to top.滚动到顶部链接出现在页面底部(靠近页脚),只有在鼠标向下滚动 200 像素后才可见,并且在滚动回顶部时应该隐藏。 WITHOUT JQUERY没有JQUERY

Here is the demo这是演示

In this demo back to top is already at the bottom.在这个演示中回到顶部已经在底部。 Is there any way to show back to top link fixed as I mention above?有什么办法可以显示我上面提到的已修复的返回顶部链接?

if you want it as simple as possible, just use:如果您希望它尽可能简单,请使用:

<a href="#" onClick="window.scrollTo(0,0)">

this will scroll you to the top of your site.这会将您滚动到您网站的顶部。

Here is the answer这是答案

HTML HTML

<a id="scroll_to_top_id"></a>

CSS CSS

#scroll_to_top_id {
  display: none;
  position: fixed;
  right: 30px;
  bottom: 30px;
  background
}

PURE JAVASCRIPT(NO JQUERY)纯 JAVASCRIPT(无 JQUERY)

/*
 *  Scroll To Top
 */

var your_header        = document.getElementById('header_id'),
    scroll_to_top   = document.getElementById('scroll_to_top_id');


window.onscroll = function(ev) {

    var  scrollTop = window.pageYOffset || document.body.scrollTop;
    if (scrollTop > your_header.offsetHeight + 100) {

        scroll_to_top.style.display = 'block';
    }
    else{
        scroll_to_top.style.display = 'none';   
    }
};

scroll_to_top.onclick = function () {
    scrollTo(document.body, 0, 100);
}

/*
 *  scroll to body top
 *  element, position and time duration
 */
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);
}

For this case, the MDN docs leave an awesome solution, we can now use the following example:对于这种情况, MDN 文档留下了一个很棒的解决方案,我们现在可以使用以下示例:

const el = document.getElementById('the-scroll-box');

el.scrollTo({
  top: 0,
  left: 0,
  behavior: 'smooth', // or can get `auto` variable
});

The behavior if have smooth value, the scrolling motion is smooth if have auto value the motion happen in one jump. behavior如果有smooth值,滚动运动是平滑的如果有auto值运动发生在一次跳跃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM