2015-02-10 18 views
-5

我在特定div中加載欄,即從頁面頂部700px。加載欄的JavaScript工作正常,但它在起始頁面被觸發,當我到達特定的div時,bar已經加載,我想要的是當我到達該div時開始加載。請幫忙。在特定div上開始加載欄javascript

的JavaScript:

<script> 

$('.numberprogress[data-percentage]').each(function() { 
    var progress = $(this); 
    var percentage = Math.ceil($(this).attr('data-percentage')); 
    $({countNum: 0}).animate({countNum: percentage}, { 
    duration: 5000, 
    easing:'linear', 
    step: function() { 
     // What todo on every count 
    var pct = ''; 
    if(percentage == 0){ 
     pct = Math.floor(this.countNum) + '%'; 
    }else{ 
     pct = Math.floor(this.countNum+1) + '%'; 
    } 
    progress.text(pct) && progress.siblings().children().css('width',pct); 
    } 
    }); 
}); 
</script> 

HTML:

<div class="middle> 
<div class="progress"><div class="numberprogress" data-percentage="80"></div> 
<div class="progressbar"><div class="progresspercent"></div></div></div> 
</div> 

CSS:

.progress{ 
    float:left; 
    width:300px; 
    height:50px; 
    color:#FFF; 
    background-color:#38B1CC; 
    margin-top:5px; 
    border-radius:4px; 
    font-family: sans-serif; 
    text-align:center; 
    font-size:0.8em; 
} 

.numberprogress{ 
    float:left; 
    height:18px; 
    width:18%; 
    color:white; 
    font-size:14px; 
    text-align:center; 
    background: rgba(0,0,0,0.13); 
    padding: 9px 0px; 
    border-radius:4px; 
    margin:5px; 
} 

.progressbar{ 
    margin-left:0px; 
    float:right; 
    border-radius:10px; 
    margin:5px; 
    height:10px; 
    width:75%; 
    background: rgba(0,0,0,0.13); 
    margin-top:18px; 
    overflow: hidden; 
} 

.progresspercent{ 
    height:100%; 
    float:left; 
    background-color:white; 
    border-radius:10px; 
} 
.middle{ 
    height:600px; 
    width:auto; 
    font-family:Bizon; 
} 

回答

0

而是加載它在DOM準備好或onload事件的,那麼當它達到那個加載它特定div。

if ($(document).scrollTop() >= $('.target-div').offset().top) { 
Your function 
} 
+0

可不可以給我的例子嗎?我無法弄清楚在我的代碼中如何做到這一點。 – Mike 2015-02-10 21:56:55

+0

這是http://stackoverflow.com/a/28442694/2442396 – 2015-02-10 22:08:07

0

要在@Syahrul答案補充,這裏是一個工作示例:a working example

$(document).scroll(function() {  
$('.numberprogress[data-percentage]').each(function() {   
    if ($(document).scrollTop() >= $(this).offset().top) { 
     animateProgress($(this)); 
    } 
});});