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

你说的曾经没有我的故事 提交于 2019-12-12 14:19:43

问题


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!


回答1:


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



回答2:


Try to use IFrame instead of Div or create a specific function using ScrollBy.



来源:https://stackoverflow.com/questions/1897573/how-to-go-to-anchor-tag-in-scrollable-div-without-having-the-whole-browser-jump

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!