2014-01-22 33 views
1

首先,我知道有類似的線程,但其中大多數使用李項目,我是geeting太混亂,使用該代碼爲我的利益。第一個和最後一個可見的項目在一個DIV與溢出

這裏是...我有一個溢出和一些最大高度的元素。在裏面我有另一個div元素和一個錨點,每個元素都有我的數據。 我希望能夠判斷父母是否已經飛越,如果是,就做點什麼。 根據我想要的最後/第一格的情況下,是可見做些事情。

有什麼比一個例子更好...所以這裏是我在jsfiddle

例子,jQuery中的基本邏輯,我想在評論中實施:

var container = $('#content_wrapper'); 
var items = container.children('.box_wrap'); 

//If div is overflown then do: 
/items.each(function() { 
    //If scroll is at top 
    //Get last element that is shown 
    //Do something 

    //Else if scroll is at bottom 
    //Get first element and do something 

    //Else if scroll is at mid range 
    //get first and last element that is shown 
    //and do something 
} 

回答

1

恐怕沒有小事這個問題的解決方案(不添加插件),但是你可以使用scroll jquery事件來觀察你的div子元素的當前位置,然後對你的邏輯進行處理。

我們可以知道,如果我們的產品具有明顯的完全,在div區域內,如果他們的CSS top屬性爲> = 0,並在同一時間主要格價值height小於(top + height當前div小孩

看看這塊代碼:

$('#content_wrapper').scroll(function() { 
    var areaHeight = $(this).height(); // gets the height of content_wrapper 

    //will receive first/last elements found 
    var first_ele = null; 
    var last_ele = null; 

    items.each(function(index, value) { 
    var top = $(this).position().top; //top position of element 
    var height = $(this).height(); 

    /* detection can be altered here */ 
    if (top > -1 && first_ele == null){ //first entirely visible element 
     first_ele = this; 
    } 
    else if (top+height > areaHeight && last_ele == null){ 
     last_ele = $(items[index-1]);//the last entirely visible was the element before 
    } 

    // those not being first or last receive data-id back 
    $(this).children().first().html($(this).children().first().attr('data-id')); 
    }); 

    //action to first element, avoid first of list 
    if(first_ele !== items[0]) 
    $(first_ele).children().first().html('test start');  
    //action to last element      
    $(last_ele).children().first().html('test end'); 
}); 

通過items這段代碼,我們可以循環檢測第一最後像前面提到的完全可見的元素。隨着他們設置,他們的html被測試消息所取代。不應接收操作的項目將使用data-id屬性覆蓋inner html

如果你想要部分有一個動作,這是在代碼中評論的塊,我可能需要調整一下,我已經用一個例子設置了一個小提琴,其中使用頂部/中部的動作/底部情況。

全部工作FIDDLEhttp://jsfiddle.net/nyupm/5/

+0

是這個樣子就不錯了!必須研究它的功能性,但這是一個巨大的幫助,非常感謝! – Dennis

相關問題