【问题标题】:.animate() query not working.animate() 查询不起作用
【发布时间】:2017-07-25 14:58:18
【问题描述】:

我想在我的静态 HTML 网站中实现一个“滚动回顶部”按钮,就像我之前做过一百万次一样。所以我添加了这段代码: (第一部分是关于让按钮在一定时间后出现,不用担心)

$( document ).ready(function() {

    $(window).scroll(function() {
        var scroll = $(document).scrollTop();
        var wheight = $(window).height();
        var hheight = wheight / 2;
        if(scroll >= hheight) {
            $('#scroller').css({'opacity': '1'});
        } else if (scroll <= hheight) {
            $('#scroller').css({'opacity': '0'});
        }
    });

    $('#scroller').click(function() {
        alert("click works!");
        $('html, body').animate({ scrollTop: 0 }, 500);
    });
});

按钮的出现和消失有效,如果我点击按钮,它也会提醒“点击有效”。但是滚动不起作用。我迷路了。我在某处读到你不应该在 CSS 中使用 height: 100% 并使用

height: auto;
min-height: 100%;

相反。那不会改变任何事情。我也尝试使用document 作为滚动元素。

如果有人可以帮助我,我很高兴!

【问题讨论】:

  • 你能提供 html 吗?如果您有html, body, #wrapper { height: 100%; },您可能需要将代码更改为$('html, body, #wrapper').animate({ scrollTop: 0 }, 500);
  • 不幸的是这也行不通:(

标签: jquery html css jquery-animate


【解决方案1】:

您的代码似乎有效:

$( document ).ready(function() {

    $(window).scroll(function() {
        var scroll = $(document).scrollTop();
        var wheight = $(window).height();
        var hheight = wheight / 2;
        if(scroll >= hheight) {
            $('#scroller').css({'opacity': '1'});
        } else if (scroll <= hheight) {
            $('#scroller').css({'opacity': '0'});
        }
    });

    $('.scroll').click(function() {
        $('html, body').animate({ scrollTop: 0 }, 500);
    });
});
* {
  box-sizing: border-box;
}
html, body {
  margin: 0;
}

body {
  background: linear-gradient(to top, red, blue);
  height: 2000px;
  border: 10px solid goldenrod;
  position: relative;
}

.scroll {
  font-size: 2em;
  position: absolute;
  bottom: 0;
  display: block;
  width: 100%;
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="scroll">scroll</button>

【讨论】:

    【解决方案2】:

    我让它工作了! 我使用了 jQuery 的精简版。 一旦我切换到正常的生产版本,一切正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-07
      • 2011-11-19
      相关资源
      最近更新 更多