【问题标题】:How can I pass an id of element to url when I scroll to it?当我滚动到它时,如何将元素的 id 传递给 url?
【发布时间】:2014-04-29 10:54:57
【问题描述】:

我在一个页面上有一组元素,其中包含 id。

客户端希望能够有一个滚动,每次滚动到它时都会将 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');
                }

                });
            });

似乎没有任何效果。

谁能指点我正确的方向?

【问题讨论】:

  • 您不会更改位置。试试window.location.href += '/#' + scrolledDivs.attr('id')

标签: javascript jquery html scroll frontend


【解决方案1】:

我相信这是您正在寻找的东西:

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));        
    });
});

【讨论】:

  • 嗯,滚动正文或窗口时不起作用?这是我遇到错误的地方。
  • 这适用于 $(window) - jsfiddle.net/bfd7w/2。它需要var bottom_of_window = $(window).scrollTop() + $(window).height();
  • 太好了,有没有办法可以将 id 切换到 url 的末尾?每次我这样做时,它只是将它们附加到 url 上并不断添加它们而不是清除之前的。
  • 你知道Regular Expressions怎么用吗?您是每次都重新加载页面还是使用window.history.pushState
  • 不,所以当您滚动时,我需要做的就是从 /#studios 切换到 /#resident-memberships。我认为 window.history.pushState 会矫枉过正
猜你喜欢
  • 2014-09-02
  • 1970-01-01
  • 2017-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-02
相关资源
最近更新 更多