3

我正在尝试使用 javascript(不是 jQuery)制作一个 gototop 按钮。我希望此按钮具有延迟效果,我可以通过以下方式实现:

    var timeOut;
    function scrollToTop() {
      if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
        window.scrollBy(0,-50);
        timeOut=setTimeout('scrollToTop()',10);
       }
      else clearTimeout(timeOut);
    }

html很简单: <div id="gototop"><a href="#header" onclick="scrollToTop();return false">Back to top</a></div>

我无法根据滚动高度显示/隐藏按钮。据我所知,以下内容应该隐藏按钮,直到页面向下滚动 600px,但这不起作用:

    var posit = window.scrollTop();
    if (posit < 900) {
        document.getElementById("gototop").style.display = 'none';
    }

为什么这个样式不生效?

我使用的完整代码是:

    var posit = window.scrollTop();
    if (posit < 900) {
        document.getElementById("gototop").style.display = 'none';
    }
    var timeOut;
    function scrollToTop() {
      if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
        window.scrollBy(0,-50);
        timeOut=setTimeout('scrollToTop()',10);
       }
       else clearTimeout(timeOut);
      }

感谢您的关注,您好。

4

2 回答 2

2

尝试将其放入 onscroll 事件处理程序中,例如:

为您的 gototop 元素添加样式,例如:

<div id="gototop" onclick="scrollToTop()" style="display:none;"> </div>     


window.onscroll = function(){
    if (window.scrollY < 900) {
        document.getElementById("gototop").style.display = 'none';
    else
        document.getElementById("gototop").style.display = 'block';
}
于 2012-12-11T10:30:25.380 回答
0

这是返回顶部按钮的完整工作代码。

<style type="text/css">
#gototop{display:none;position:fixed;right:28px;bottom:10px;z-index:100;}
#gototop a{font-size:14px;font-weight:bold;display:block;padding:5px;text-decoration:none;color:#fff;background:#000;opacity:0.5;border:1px solid #aaa;}
#gototop a:hover{color: #000;text-decoration:underline;background-color:#fff;border: 2px solid #aaa;opacity:0.5;}
</style>

<script type="text/javascript" language="javascript">

// document.documentElement.scrollTop makes it work in Chrome and IE
// 400 is the point from which the button starts showing, you can change it to your needs

gototop = document.getElementById("gototop");

window.onscroll = function(){
    if (window.scrollY < 400 || document.documentElement.scrollTop < 400) {
        gototop.style.display = 'none';
}
    if (window.scrollY > 400 || document.documentElement.scrollTop > 400)
        gototop.style.display = 'block';
}

var timeOut;
function scrollToTop() {
    if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
        window.scrollBy(0,-50);
        timeOut=setTimeout('scrollToTop()',10);
    }
    else clearTimeout(timeOut);
}
</script>

<div id="gototop"><a href="#header" onclick="scrollToTop();return false">Back to Top</a></div>
于 2012-12-12T06:44:24.523 回答