簡體   English   中英

當div元素出現在視口中時觸發動畫

[英]Trigger animation when div element appears in viewport

我正在使用此答案中的滾動觸發器來構建一個progressbar.js動畫,一旦整個進度條div在視口中,就會觸發該動畫。

動畫正常運行而沒有觸發器,僅在頁面加載時運行。 但是,當元素滾動到完整視圖時,我無法觸發它。

下面的示例代碼在頂部具有div間隙,因此您可以在動畫開始之前向下滾動,盡管顯然這是我無法使用的部分。

 function privacyScoreCircle() { // progressbar.js circle var bar = new ProgressBar.Circle(document.getElementById('privacy-score-circle'), { color: '#aaa', // This has to be the same size as the maximum width to // prevent clipping strokeWidth: 4, trailWidth: 4, easing: 'easeInOut', duration: 1400, text: { autoStyleContainer: false }, from: { color: '#dddddd', width: 4 }, to: { color: '#aaaaaa', width: 4 }, // Set default step function for all animate calls step: function(state, circle) { circle.path.setAttribute('stroke', state.color); circle.path.setAttribute('stroke-width', state.width); var value = Math.round(circle.value() * 100); if (value === 0) { circle.setText(''); } else { circle.setText(value + '%'); } } }); bar.text.style.fontFamily = '"Montserrat", sans-serif'; bar.text.style.fontSize = '1.7rem'; bar.trail.setAttribute('stroke-linecap', 'round'); bar.path.setAttribute('stroke-linecap', 'round'); //bar.animate(0.97); // <-- ANIMATION CAN BE TRIGGERED INSTANTLY USING THIS } privacyScoreCircle(); // Check if element is scrolled into view function isScrolledIntoView(elem) { var docViewTop = $(window).scrollTop(); var docViewBottom = docViewTop + $(window).height(); var elemTop = $(elem).offset().top; var elemBottom = elemTop + $(elem).height(); return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)); } function Utils() { } Utils.prototype = { constructor: Utils, isElementInView: function(element, fullyInView) { var pageTop = $(window).scrollTop(); var pageBottom = pageTop + $(window).height(); var elementTop = $(element).offset().top; var elementBottom = elementTop + $(element).height(); if (fullyInView === true) { return ((pageTop < elementTop) && (pageBottom > elementBottom)); } else { return ((elementTop <= pageBottom) && (elementBottom >= pageTop)); } } }; var Utils = new Utils(); var isElementInView = Utils.isElementInView($('#privacy-score-circle'), false); if (isElementInView) { bar.animate(0.97); } 
 #gap { height: 500px; } #privacy-score-circle { margin: auto; width: 200px; height: 200px; position: relative; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/progressbar.js/1.0.1/progressbar.min.js"></script> <div id="gap">Scroll down to activate animation</div> <div id="privacy-score-circle"></div> 

您應該在代碼中應用以下更改:

  1. 您在privacyScoreCircle()函數中聲明了bar變量。 在函數內部定義的變量不能從函數外部訪問。 因此,將其定義為全局變量。
  2. 滾動窗口時應執行動畫。

您可以在此處查看正確運行的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM