Twitter Bootstrap scrollspy always selecting last element

后端 未结 13 1571
旧巷少年郎
旧巷少年郎 2020-12-08 04:22

I have an issue with scrollspy, recreated in this fiddle: http://jsfiddle.net/jNXvG/3/

As seen in the demo, the ScrollSpy plugin always keeps the last menu item sele

相关标签:
13条回答
  • 2020-12-08 05:09

    Make sure you're not mixing implementations. You don't need $('#content).scrollspy() if you have data-spy="scroll" data-target=".bs-docs-sidebar" on your body tag.

    0 讨论(0)
  • 2020-12-08 05:11

    I had a similar issue where scroll spy would not work on anything but a body tag so I actually went into the bootstrap js found the Scroll spy (SCROLLSPY CLASS DEFINITION) section and changed this line:

    , $element = $(element).is('body') ? $(window) : $(element)

    to this:

    , $element = $(element).is('body') ? $(window) : $(window) //$(element)

    (note that the element after the // is a comment so I don't forget I changed it)

    And that fixed it for me.

    0 讨论(0)
  • 2020-12-08 05:12

    FYI: To get my desired effect (same one as on the Twitter Bootstrap docs page) I needed to set 'body' as my target element...I could not get scrollspy'ing to work by using the immediate parent of the elements I wanted to spy as the target.

    (It just auto-selected the my last element always)

    0 讨论(0)
  • 2020-12-08 05:16

    I think that this might be a bug in ScrollSpy.

    I also had the same problem and when I stepped through the code I could see that the offset for all the targets were the same (-95px). I checked where these were being set and it was using the position() function. This returns the position of the element relative to the offset of the parent.

    I changed this to use the offset() function instead. This function returns the position of the element relative to the offset of the page. Once I did this then it worked perfectly. Not sure why this isn't the default behaviour.

    The reason that the position() function wasn't working in my case was because I had to have an empty div which was actually absolutely positioned 95px above the top of its container. I needed this as my target so that the headings weren't hidden behind my header that was fixed to the top of the page.

    0 讨论(0)
  • 2020-12-08 05:20

    You need to attach the ScrollSpy to the element that is going to trigger scroll events, rather than the menu that is going to reflect the scroll position:

    $('#content').scrollspy();​
    

    JSFiddle

    0 讨论(0)
  • 2020-12-08 05:23

    When I was trying to figure out this issue, I used some of what Mehdi Benadda said and added position: relative; to the body. I added this to the stylesheet:

    body {
      position: relative;
      height: 100%;
    }
    

    Hopefully this helps someone in the future.

    0 讨论(0)
提交回复
热议问题