2017-10-18 55 views
0

我有一個腳本,根據所選框打開和關閉各個部分。中間對齊視圖與滾動效果在部分

我需要這些部分是在視口的中間一次點擊(用流暢的動畫效果,如果可能的話)

這裏是我當前的腳本:

$(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」爲中心在它打開後的視口中。

回答

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); 
+0

是否有沒有辦法讓我已經在函數中,並使其通過targetElement變量? –

+0

把scrollTo函數放在jquery scope之外,這兩行代碼放在你想調用動作的地方: 'var targetElement = $($(this).data('target'))。offset( )。最佳; scrollTo(document.body,targetElement,1000);' –