2016-08-11 61 views
0

我想在頁面滾動到某個元素時運行動畫。這工作正常。 但主要的問題是動畫運行一次又一次。我只想運行一次動畫。頁面滾動到某個元素觸發事件

這是我用作參考的代碼。

HTML

<div>Scroll Down</div> 
<h1 id="scroll-to">I am The H1</h1> 

JS

$(window).scroll(function() { 
    var hT = $('#scroll-to').offset().top, 
     hH = $('#scroll-to').outerHeight(), 
     wH = $(window).height(), 
     wS = $(this).scrollTop(); 
    console.log((hT-wH) , wS); 
    if (wS > (hT+hH-wH)){ 
    alert('you have scrolled to the h1!'); 
    } 
}); 

CSS

div { 
    height:800px; 
    background:red; 
} 


http://jsfiddle.net/n4pdx/ 

回答

0

設置標誌,當用戶滾動到特定的div。像:

var flag = true; 
$(window).scroll(function() { 

    var hT = $('#scroll-to').offset().top, 
    hH = $('#scroll-to').outerHeight(), 
    wH = $(window).height(), 
    wS = $(this).scrollTop(); 
    console.log((hT-wH) , wS); 
    if (wS > (hT+hH-wH) && flag){ 
    alert('you have scrolled to the h1!'); 
    flag = false; 
    } 
}); 
+0

如何更改標誌的值而不刷新頁面? 如果用戶再次上下滾動?因爲再次滾動我想再次運行動畫 –

+0

你的意思是,當用戶再次滾動時你想要動畫? –

1

你可以把一個標誌,當你已經動畫滾動:

var scrolled = false; 

$(window).scroll(function() { 
    var hT = $('#scroll-to').offset().top, 
     hH = $('#scroll-to').outerHeight(), 
     wH = $(window).height(), 
     wS = $(this).scrollTop(); 
    console.log((hT-wH) , wS); 
    if (wS > (hT+hH-wH)){ 
    if(!scrolled){ 
     scrolled = true; 
     alert('you have scrolled to the h1!'); 
    } 
    } 
    else{ 
     scrolled = false; 
    } 
}); 

在這個例子中,我重新設置標誌時,用戶上去。

相關問題