最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot properly refresh Bootstrap scrollspy spying on <body> element - Stack Overflow

programmeradmin2浏览0评论

I've been referencing this post regarding Bootstrap's scrollspy ponent. In my code, I instantiate a new scrollspy to spy on the body element using:

$("body").scrollspy({ offset: 25 });

Later on in my code, I make an AJAX call and add/remove elements from the page. This causes the scrollspy to be misaligned, so I need to refresh the scrollspy. I have tried performing this refresh operation many ways, such as:

$("body").scrollspy("refresh");

and

$('[data-spy="scroll"]').each(function () {
  $(this).scrollspy('refresh');
}); 

However, neither of these code snippets bring about any change in the behavior of the scrollspy. I believe this is because the scrollspy is spying directly on the body element, but I am unsure of how to have the scrollspy refresh following my AJAX calls. Does anyone know how I might refresh my scrollspy?

I've been referencing this post regarding Bootstrap's scrollspy ponent. In my code, I instantiate a new scrollspy to spy on the body element using:

$("body").scrollspy({ offset: 25 });

Later on in my code, I make an AJAX call and add/remove elements from the page. This causes the scrollspy to be misaligned, so I need to refresh the scrollspy. I have tried performing this refresh operation many ways, such as:

$("body").scrollspy("refresh");

and

$('[data-spy="scroll"]').each(function () {
  $(this).scrollspy('refresh');
}); 

However, neither of these code snippets bring about any change in the behavior of the scrollspy. I believe this is because the scrollspy is spying directly on the body element, but I am unsure of how to have the scrollspy refresh following my AJAX calls. Does anyone know how I might refresh my scrollspy?

Share Improve this question edited May 23, 2017 at 12:10 CommunityBot 11 silver badge asked Aug 12, 2014 at 13:22 PaulDapolitoPaulDapolito 8246 silver badges12 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

It appears that it is not possible to refresh a scrollspy that is set to spy on the body element via a call to $("body").scrollspy(). In order to use the refresh functionality documented on the Bootstrap website, I had to explicitly declare the data-spy and data-target attributes of the body tag (where scrollingNav is the id of the nav bar in which to visualize the scrolling):

<body data-spy="scroll" data-target="#scrollingNav">

Then, to refresh this scrollspy when elements were dynamically added/removed from the page, I used the following method:

function refreshScrollSpy() {
    $('[data-spy="scroll"]').each(function () {
        $(this).scrollspy('refresh');
    }); 
};
发布评论

评论列表(0)

  1. 暂无评论