2013-02-03 14 views
1

我試圖創建相同的「動畫」中心如何只加載評論所見有:當帖子達到窗口的使用jQuery

http://letmehaveblog.blogspot.it/?view=classic

後的意見是,只有當加載該職位到達窗口的中心。我的代碼工作正常,如果我只更改包含註釋的div的CSS顯示或不透明屬性(帖子的高度未修改),但當我使用slideUp/slideToggle作爲我想模擬一個通過ajax的php腳本。我負責的這段JavaScript代碼:

$(document).ready(function() { 
var winWidth, winHeight; 

function show_post_content() { 

/* Check the location of each desired element */       
$('.post').each(function(i){  

var top_of_object = $(this).position().top;  
var top_of_window = $(window).scrollTop();                 
var bottom_of_object = $(this).position().top + $(this).outerHeight(); 
var bottom_of_window = $(window).scrollTop() + $(window).height();   

/* If the object is completely visible in the window, fade it in */ 
//if(bottom_of_window > bottom_of_object){ 
if(top_of_object < parseInt(winHeight/2)) {        

    //$(this).children('.comments').css('display','block');                  
    //$(this).children('.comments').animate({'opacity':'1'},500); 
    //$(this).children('.comments').fadeIn(500); 
    //$(this).children('.comments').animate({'opacity':'1'},500); 
    $(this).children('.comments').slideToggle('slow'); 

}                  

});  

}  

function hide_post_content() { 

    $('.post').each(function(i){ 

    $(this).children('.comments').slideUp(); 

    }); 

}  

function init() { 
    winWidth = $(window).width(); 
    winHeight = $(window).height(); 

    hide_post_content(); 
    show_post_content(); 
} 

init(); 

$(window).resize(function() { 
    init(); 
}); 

/* Every time the window is scrolled ... */ 
$(window).scroll(function(){  
    show_post_content();  
});  

}); 

的HTML是一個:

<div class="post">Post 
<div class="comments">Comments</div> 
</div> 
<div class="post">Post 
<div class="comments">Comments</div> 
</div> 
<div class="post">Post 
<div class="comments">Comments</div> 
</div> 
... 

用CSS: 。員額{ 不透明度:1;
width:600px; min-height:100px; background-color:#ffffff;
display:block; padding:0px; margin:30px auto;
border:1px solid#000000; }

.comments{ 
    opacity: 1; 
    width: 580px; 
    height: 50px; 
    display: none; 
    margin:100px 0 0 0; 
    padding:10px; 
    background-color: #aaaaaa;  
} 

我搜索過這裏的答案,但無法找到一個可能把我在正確的道路上。任何想法或建議?非常感謝,埃裏克

回答

0

slideToggle函數異步執行其動畫。它也改變了後面的帖子元素的位置。因此,在each函數中,您調用slideToggle,然後在slideToggle完成更改其他後期元素的位置之前繼續進行下一次迭代。這是一個問題。另一個是當您滾動時,滾動事件將會激發很多次。比執行show_post_content所需的時間多。

因此,這裏有一些建議:

  1. 作爲第一步,要確保show_post_content運作的,你想要的方式,無論滾動事件。您應該從ready函數中取出show_post_content(您必須在開頭添加winHeight = $(window).height();)。然後,您可以在Chrome或Firefox中從控制檯執行它。在頁面上滾動到不同位置並確保它按照您的預期方式工作後,執行此操作。您可能想要更改功能,以在一個帖子完成後停止,或者只在動畫完成後才能繼續下一個功能(slideToggle允許您在完成時傳遞迴調函數)。

  2. 限制scroll事件。有this插件,或者您可以搜索SO來尋找其他選項。更好的辦法是在用戶停止滾動時僅運行show_post_content。這很難,但你可以開始here

+0

非常感謝傑夫。偉大的建議。 –

相關問題