【问题标题】:how to scroll slowly from top to bottom and bottom to top when click on same div?单击同一个div时如何从上到下和从下到上缓慢滚动?
【发布时间】:2015-02-19 16:58:20
【问题描述】:
$(document).ready(function() {
      $("#Wrapper").click(function () {
    var th = $(this);
    if (!th.hasClass('down')) {
        console.log("ret");
        th.addClass('down').stop(true).animate({
            "top": "50px"
        }, 1000, function() {
            $('body').scrollTop(th.height());
        });
    } else {
        console.log("sdffsdsff");
        th.removeClass('down').stop(true).animate({
            "top": "-400px"
        }, 1000, function() {
            $('body').scrollTop(th.scrollTop());
        });
    }
});

});

我有这个 jquery 代码,用于在单击包装器时从上到下和从下到上滚动。 此代码有效,但我希望当单击“包装器”div 时,它应该从顶部 tp 底部和底部到顶部缓慢滚动

这是我原来的小提琴

http://jsfiddle.net/HtTXB/9/

怎么做?更多改进动画的建议非常感谢。在此先感谢。

【问题讨论】:

  • 平滑滚动已被询问和回答。你可以看看这个类似的问题Scroll smoothly to specific element on page我看不出你的问题有什么不同。
  • 它突然滚动我想慢慢滚动。看小提琴
  • 当点击“wrapper” div 时,它应该会缓慢平滑地滚动。
  • 让我们在点击“包装”div 后说。在 1 秒内滚动到页面的一半,在 2 秒内滚动到页面底部。?
  • 您是否有任何理由操纵偏移top 属性?元素是浮动的,并且位置没有设置为相对,所以它不会工作。

标签: jquery scroll


【解决方案1】:

您当前所做的是为包装器本身的位置设置动画,这是您看不到的,当此动画完成后,您会跳转到“顶部/底部”。您应该为滚动设置动画,而不是位置:

$(document).ready(function() {
  $("#Wrapper").click(function () {
    var th = $(this),
        toSCroll = $('html,body');
    if (!th.hasClass('down')) {
      // animate the scrolling for body/html
      toScroll.stop(true).animate({
        scrollTop: th.height()
        }, 1000, function() {
          // add class when ani is done
          th.addClass('down');
        });
    } else {
      toScroll.stop(true).animate({
        scrollTop: th.get(0).offsetTop /* or 0 for page top*/
      }, 1000, function() {
        th.removeClass('down');
      });
    }
  });
});

Fiddle is here.

【讨论】:

  • 是的,它的工作兄弟。它是一个很好的答案。非常感谢您宝贵的时间。请给我的问题复习一下
猜你喜欢
  • 1970-01-01
  • 2015-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多