"向上滚动按钮"不是在窗口,而是在某个div可能吗?

时间:2016-04-19 13:37:58

标签: javascript jquery html css

这是我的问题!

我有一个网站的向上滚动按钮,在用户从window向下滚动50px后激活自己。在我的情况下,虽然用户在名为#pages的div中滚动。我试图在jquery代码中替换窗口,但它似乎不起作用。有什么想法吗?

.scrlTp将是按钮本身。

如果问题不够明确请问,我会非常感谢您的时间!

我的代码现在:

$(document).ready(function(){

    //Check to see if the window is top if not then display button
    $(window).scroll(function(){
        if ($(this).scrollTop() > 50) {
            $('.scrlTp').fadeIn();
        } else {
            $('.scrlTp').fadeOut();
        }
    });

    //Click event to scroll to top
    $(window).click(function(){
        $('html, body').animate({scrollTop : 0},800);
        return false;
    });

});

2 个答案:

答案 0 :(得分:2)

您还必须替换html, body



$(document).ready(function() {

  //Check to see if the window is top if not then display button
  $("#pages").scroll(function() {
    if ($(this).scrollTop() > 100) {
      $('.scrlTp').fadeIn();
    } else {
      $('.scrlTp').fadeOut();
    }
  });

  //Click event to scroll to top
  $(".scrlTp").click(function() {
    $("#pages").animate({
      scrollTop: 0
    }, 800);
    return false;
  });

});

#pages {
  height: 100px;
  width: 200px;
  overflow-y: scroll;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scrlTp" style="display: none">to top</div>
<br />
<div id="pages">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugiat fuga atque blanditiis nemo incidunt quibusdam obcaecati! Nisi ullam est provident corporis nesciunt excepturi iste ad, alias temporibus esse ipsum rerum!Lorem ipsum dolor sit amet, consectetur
  adipisicing elit. Dignissimos totam neque distinctio laborum cumque vitae, officiis architecto facilis accusamus quam consequatur tempora illo quia perferendis, alias autem magnam doloremque dolor!Lorem ipsum dolor sit amet, consectetur adipisicing
  elit. Magnam, quia amet beatae. Amet id labore dignissimos vitae libero, dolorum, quisquam laudantium, earum necessitatibus nostrum ex vel laborum eaque nesciunt facere.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque saepe quis consectetur
  explicabo natus nulla, provident voluptates placeat ipsam animi similique officia qui nihil, rerum earum ea deserunt ullam dolore!
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

看到这段代码:

 $('html, body').animate({
        scrollTop: $("#elementtoScrollToID").offset().top
 }, 2000);

- )