简体   繁体   English

没有jQuery的返回页首按钮

[英]Back to top button without jQuery

I want to create a button "Back to top" with javascript. 我想使用javascript创建一个“返回页首”按钮。 My code (which I found on StackOverflow) does not work when I click the button nothing happens. 当我单击按钮时,什么都没发生,我的代码(在StackOverflow上找到)无法正常工作。

HTML 的HTML

     <button type="button" id="backtotop_js">To the top</button>

JAVASCRIPT JAVASCRIPT

     document.getElementById('backtotop_js').onclick = function () {
        scrollTo(document.documentElement, 0, 1250);
     };
     function scrollTo(element, to, duration) {
         var start = element.scrollTop,
             change = to - start,
             currentTime = 0,
             increment = 20;

         var animateScroll = function(){        
             currentTime += increment;
             var val = Math.easeInOutQuad(currentTime, start, change, duration);
             element.scrollTop = val;
             if(currentTime < duration) {
                 setTimeout(animateScroll, increment);
             }
         };
         animateScroll();
     }

     Math.easeInOutQuad = function (t, b, c, d) {
        t /= d/2;
        if(t < 1) 
           return c/2*t*t + b;
        t--;
        return -c/2 * (t*(t-2) - 1) + b;
     };

(I'm using Chrome and Firefox) (我正在使用Chrome和Firefox)

Where's the mistake? 哪里错了?

Will make the scroll to top without animation in vanilla JS 将在香草JS中将滚动到顶部而不显示动画

document.getElementById('backtotop_js').onclick = function () {    
    document.documentElement.scrollTop = 0;
}

EDIT: changed document.getElementsByTagName('body')[0] to document.documentElement as per Rudie's comment below. 编辑:根据Rudie在下面的评论,将document.getElementsByTagName('body')[0]更改为document.documentElement。

Definition and Usage (of document.document.Element) 定义和用法(document.document.Element的)

The documentElement property returns the documentElement of a document, as an Element object. documentElement属性返回文档的documentElement作为Element对象。

For HTML documents the returned object is the HTML element. 对于HTML文档,返回的对象是HTML元素。

Note: If the HTML element is missing, the return value is null. 注意:如果缺少HTML元素,则返回值为null。

http://www.w3schools.com/jsref/prop_document_documentelement.asp http://www.w3schools.com/jsref/prop_document_documentelement.asp

you shoud scroll not the html element but instead the body... as vikton was giving an example. 您应该滚动滚动而不是html元素,而是滚动正文……就像vikton在举一个例子。

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

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