2014-04-29 25 views
2

我在頁面上有一組元素,其中包含ID。當我滾動到它時,如何將元素的id傳遞給url?

客戶端希望能夠在每次滾動頁面時都能夠將id附加到url的末尾。

因此,繼承人的標記:

HTML:

<section class="body-large scrolled" id="drop-in-membership"> 

</section>  

     <section class="body-large scrolled" id="hotdesk-membership"> 

</section>  

     <section class="body-large scrolled" id="resident-membership"> 

</section>  

     <section class="body-large scrolled" id="studios"> 

</section> 

JS:

$(window).scroll(function() { 

       var winTop = $(this).scrollTop(); 
       var $scrolledDivs = $('.scrolled'); 

       $.each($scrolledDivs, function(item) { 
        if($(item).offset().top == winTop) { 

        //console.log(this.attr('id')); 
        window.location.href + scrolledDivs.attr('id'); 
       } 

       }); 
      }); 

一切似乎是工作。

任何人都可以指出我正確的方向嗎?

+1

你不」不改變位置。試試'''window.location.href + ='/#'+ scrolledDivs.attr('id')''' – 3y3

回答

2

我相信這是你正在尋找的那種東西:

http://jsfiddle.net/bfd7w/

function CheckScroll(el) { 
    var top_of_object = el.offset().top; 
    var bottom_of_window = $('.window').height(); 
    if (bottom_of_window >= top_of_object) { 
     $('#result').text('ID ("'+el.attr('id')+'") is now showing'); 
    }  
} 

$('.window').scroll(function(){ 
    $('section').each(function() { 
     CheckScroll($(this));   
    }); 
}); 

編輯:

對於窗口滾動: http://jsfiddle.net/bfd7w/3/

function CheckScroll(el) { 
    var top_of_object = el.offset().top; 
    var bottom_of_window = $(window).scrollTop() + $(window).height(); 
    if (bottom_of_window >= top_of_object) { 
     $('#result').text('ID ("'+el.attr('id')+'") is now showing'); 
    }  
} 

$(window).scroll(function(){ 
    $('section').each(function() { 
     CheckScroll($(this));   
    }); 
}); 
+0

Negative,爲什麼?... –

+1

Upvoting抵消不必要的downvote。 –

+0

嗯,滾動身體或窗口時不起作用?這是我遇到錯誤的地方。 –

相關問題