2012-10-18 130 views
0

我正在嘗試構建一個'scrollSpy'類型的函數。我不知道如何將一個參數與一個對象中的某些值進行比較,並返回(數值上)最高值的名稱。比較offset()。top與對象屬性

我有一些標記:

<ul class="nav"> 
    <li><a href="a"></a></li> 
    <li><a href="b"></a></li> 
    <li><a href="c"></a></li> 
    <li><a href="d"></a></li> 
    <li><a href="e"></a></li> 
    <li><a href="f"></a></li> 
</ul> 

<section id="a" class="scrollspy"></section> 
<section id="b" class="scrollspy"></section> 
<section id="c" class="scrollspy"></section> 
<section id="d" class="scrollspy"></section> 
<section id="e" class="scrollspy"></section> 
<section id="f" class="scrollspy"></section> 

還有一些腳本,創建一個對象包括各section,其距離的像素從頂部:

var obj = { 
    sectionOffset: {}, 
    scrollSpy: function (scrolled) { 
     // This should look in the object with the offset values, and from all 
     // the values that (scrolled) is higher than, take the largest, and 
     // return its name. 
    } 
} 


$(function() { 

    $(window).scroll(function() { 
     obj.scrollSpy($(document).scrollTop()); 
    }); 

    // Create an object consisting of all elements I want to 'spy' on. 
    // Names and values are made of element ID and top offset respectively. 
    $('.scrollspy').each(function() { 
     obj.sectionOffset[$(this).attr('id')] = (parseInt($(this).offset().top)); 
    }); 

}); 

後,我依次通過我想要的元素它會產生如下對象:

{ 
    d: 5195, 
    b: 3245, 
    a: 1319, 
    f: 5682, 
    c: 2139, 
    e: 3343 
} 

要明確,如果th e用戶在頁面上滾動3000px,函數應該返回c

回答

1
scrollSpy: function (scrolled) { 

    var highest = 0, highestName = null; 

    // iterate through the offsets 
    $.each(obj.sectionOffset, function(name, val) { 
     // check that scrolled is higher than the value, and that it's the highest found so far 
     if (scrolled > val && val > highest) { 
      highest = val; 
      highestName = name; 
     } 
    }); 

    return highestName; 
} 
+0

我打算嘗試將對象轉換爲數組,然後將其從最高位排序到最低位,並將滾動值與該數值進行比較。你救了我的麻煩,因爲這工作得很好!乾杯。 –

0
$('.scrollspy').each(function() 
{ 
    if(($(this).offset().top + $(this).height()) > 0) 
    { 
     //this is the one you are looking for. 

     return false; //break the loop. 
    } 
}); 

這會像scrollSpy fiddle

+0

你確定嗎?我在'$(window).scroll()'中運行了這個函數,它給了我''.scrollspy''元素。看起來好像你將每個元素的高度+偏移量與0進行比較。這沒有多大意義。 –

+0

如果div的頂部不是通過滾動它的頂部將是負面的。所以top + height> 0,仍然是可見的。無形div的頂部+高度將小於零。所以第一個div(top + height)> 0就是你需要的。 – user10

+0

你可以撥弄你嘗試過的代碼嗎? – user10