2017-09-07 19 views
0

我有一個腳本,當我滾動到一個元素時,它會被計數到一個數字,但它沒有理由停止在Chrome/Firefox中工作。但它在Edge中工作正常。countTo腳本在chrome/firefox的最後一個版本中無法使用

我試着清除緩存和Cookie並禁用了擴展,但它仍然不起作用。

$(function() { 
 
    var oTop = $('.stats').offset().top - window.innerHeight; 
 
    $(window).scroll(function() { 
 

 
    var pTop = $('body').scrollTop(); 
 
    if (pTop > oTop) { 
 
     start_count(); 
 
    } 
 
    }); 
 
}); 
 
var executed = false; // <= variable to false. 
 

 
function start_count() { 
 

 

 
    if (!executed) { // <= make sure it didn't executed before. 
 

 
    $('.stats h1').countTo({ 
 
     onComplete: function() { 
 
     var elementToPrepend = '<span style="margin-left:4px;">+</span>'; 
 
     $(elementToPrepend).hide().appendTo(this).fadeIn(); 
 

 
     } 
 
    }); 
 

 
    executed = true; // <= the count() function already executed 
 

 
    } 
 

 
}
.empty-space { 
 
    height: 500px; 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-countto/1.2.0/jquery.countTo.js"></script> 
 
<div class="empty-space"> 
 
    scroll down... 
 
</div> 
 
<div class="stats"> 
 
    <h1 data-from="200" data-to="2000" data-speed="1750" data-refresh-interval="50">200</h1> 
 
</div> 
 
<div class="empty-space"> 
 
</div>

演示鏈接:https://jsfiddle.net/30w9kbfj

鉻:版本61.0.3163.79(正式版本)(64位)。

Firefox:版本55.0.3(64位)。

操作系統: Windows 10 64位。

如果它不適合你嘗試使用Edge並讓我知道,任何幫助表示讚賞。

+0

在鉻中工作 – anu

+0

@anu whats your chrome's version? – ExillustX

+0

它的工作也在IE 11中,FF和鉻 – CodeHacker

回答

0

所以問題是Element.scrollTop在Chrome/Firefox中得到了更新,無論如何。

我找到了一個解決方法,將Element.scrollTopdocument.scrollingElement.scrollTop組合起來,使其跨瀏覽器。

$(document.scrollingElement || "body").scrollTop(); 

Source

Document.scrollingElement

Element.scrollTop