When linking to #, stay in current position on page [duplicate]

限于喜欢 提交于 2021-02-05 06:38:15

问题


I have an 'a' link on my website that has a jQuery function attached to it inside my page. This link's 'href' is '#', as the page does not need to reload for my jQuery. However, whenever the link is clicked, it takes you to the top of the page again. This is annoying, as the link is quite far down, so you have to find your reading position again. Is there a way to...

  • Stop the link from taking you back to the top (maybe with JavaScript?)
  • Or have an alternative to '#' that does the same job, but doesn't take you to the top of the page.

回答1:


href="#" means "Link to the top of the page", so you should definitely be looking for something to use instead of it.

Links go places, and you don't want to go anywhere, so you shouldn't be using a link.

Use a button instead.

<button type="button">Label</button>

This assumes that you absolutely cannot use progressive enhancement so that if the JavaScript fails (which it will) then loading a new page will give the same end result (albeit less efficiently).

If you can use progressive enhancement then you should use a link to something useful:

<a href="/handle/it/on/the/server">Label</a>

and then prevent the default action:

jQuery("a").on("click", handler);

function handler(event) {
    doSomethingWithJS();
    event.preventDefault();
}



回答2:


As an alternative to @Quentin's answer, if you are using links because you want to "go somewhere", but just not a reloaded / new page, use a semantic fragment identifier instead:

body { font-size: 28px; } /* for testing */
<p><a href="#my-section">My section</a></p>
<p><a href="#my-section">My section</a></p>
<p><a href="#my-section">My section</a></p>
<p><a href="#my-section">My section</a></p>
<p><a href="#my-section">My section</a></p>
<p><a href="#my-section">My section</a></p>
<p><a href="#my-section">My section</a></p>
<p><a href="#my-section">My section</a></p>
<p><a href="#my-section">My section</a></p>
<p><a href="#my-section">My section</a></p>
<p><a href="#my-section">My section</a></p>
<p><a href="#my-section">My section</a></p>


来源:https://stackoverflow.com/questions/34975699/when-linking-to-stay-in-current-position-on-page

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