简体   繁体   中英

How to go to anchor tag in scrollable div without having the whole browser jump down?

I'm building a simple glossary widget as part of a larger project for a client. The content of the glossary is enclosed within a scrollable div (overflow:auto). Each letter has an anchor tag associated with it (#a, #b, #c, etc). Above the scrollable div is a div which contains every letter of the alphabet. Clicking on one of these letters takes the user down to that letter's definitions in the scrollable div. This works, but an unintended side effect is that the entire window jumps down to the anchor, which is confusing and annoying to the user.

Here is the widget, stripped down a bit and with a bunch of <br /> 's to let you see what I mean.

http://www.nitrohandsome.com/clients/topics/glossary-widget/

I had tried a few different javascript ideas I cobbled together from some Googling, but nothing was working, so i just got rid of everything but the actual go to anchor code (I'm a pretty big JS newbie). So right now, clicking on any of the letters executes this javascript function, with the anchor tag passed to it:

    function jumpToAnchor(myAnchor) {
   window.location = String(window.location).replace(/\#.*$/, "") + myAnchor;
  }

How can I pull this off so the overall window doesn't jump each time a link is clicked?

Thanks in advance!

If you're using jQuery, you can try the scrollTo plugin. Also, to edit just the hash portion or the URL, you can just do

function jumpToAnchor(myAnchor) {
   window.location.hash = myAnchor;
}

尝试使用IFrame而不是Div或使用ScrollBy创建特定函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM