中间对齐视口与部分滚动效果

时间:2017-10-18 09:31:54

标签: javascript jquery html

我有一个脚本可以根据所选的框打开和关闭各个部分。

一旦点击,我需要将这些部分放在视口的中间(如果可能的话,使用平滑的动画)

这是我目前的剧本:

$(function() {
  $('.box').each(function() {
    var targetElement = $($(this).data('target'));
    targetElement.slideUp()
    $(this).click(function() {
      if(targetElement.is(':visible')) {
        targetElement.slideUp();
        adjustHeight();
        $("element").paroller();
      } else {
        targetElement.slideDown()
        targetElement.siblings('.section').slideUp()
        adjustHeight();
        $("element").paroller();
      }
    })
  })
});

我需要' targetElement'在打开后在视口中居中。

1 个答案:

答案 0 :(得分:0)

我使用了一个我发现为滚动设置动画的功能, 传递你想要滚动的元素和滚动到的滚动偏移。

function scrollTo (element, to, duration) {
    var start = element.scrollTop,
        change = to - start,
        currentTime = 0,
        increment = 20;

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

var targetElement = $($(this).data('target')).offset().top;
scrollTo(document.body, targetElement, 1000);
相关问题