带有 href="#" 的链接与 jquery Slidetoggle 一起使用时将页面滚动到顶部

发布于 2024-08-17 07:18:48 字数 570 浏览 4 评论 0 原文

可能的重复:
当点击触发 JavaScript 的链接时,如何阻止网页滚动到顶部?

我正在使用 jquery 的 Slidetoggle 来显示/隐藏 div。 控制滑动的元素是一个文本链接(<\a> 内有一些文本) 其中有 href="#" 所以它看起来像一个链接(下划线,光标变化)。

问题是,点击链接时,除了滑动效果之外, 页面滚动到顶部。

我尝试用 href="" 替换 href="#" 但这会禁用 div 显示/隐藏效果。 我想我可以添加到标签 Name="somename" ,然后将 href 设置为 href="#somename" 但我宁愿不使用这样的技巧。

为什么 href="#" 将页面滚动到顶部?

任何想法将不胜感激

Possible Duplicate:
How do I stop a web page from scrolling to the top when a link is clicked that triggers javascript?

I'm using jquery's slidetoggle to show/hide divs.
the element that controls the sliding is a text link ( some text inside <\a>)
which has href="#" so it will look like a link (underline, cursor change).

the problem is that when the link is clicked, in addition to the sliding effect,
the page scrolls to top.

i tried replacing href="#" with href="" but that disables the div show/hide effect.
i guess i could add to the tag Name="somename" and then set the href to href="#somename"
but i would rather not use tricks like that.

why is href="#" scrolling the page to its top?

any ideas would be highly appreciated

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

亢潮 2024-08-24 07:18:48

几个选项:

  1. return false; 放在点击处理程序的底部,这样 href 就不会被跟随。
  2. 将 href 更改为 javascript:void(0);
  3. 在处理程序中的事件上调用 preventDefault

    函数( e ) {
      e.preventDefault();
      // 你的事件处理代码
    }
    

Several options:

  1. Put return false; at the bottom of your click handler and the href wont be followed.
  2. Change the href to javascript:void(0);
  3. Call preventDefault on the event in your handler:

    function( e ) {
      e.preventDefault();
      // your event handling code
    }
    
醉南桥 2024-08-24 07:18:48

您需要将 return false; 添加到您的点击处理程序中。
这将阻止浏览器执行点击的默认操作。

You need to add return false; to your click handler.
This will prevent the browser from executing the default action for the click.

半世蒼涼 2024-08-24 07:18:48

其他人已经给你解决方案了。但为了具体回答您的问题,# 指的是当前页面。由于标签的解释是将标签的顶部带入视图,因此单击 # 标签会将您滚动到当前页面的顶部。

Others have given you solutions. But to specifically answer your question, # refers to the current page. And since the interpretation of tags is to bring the top of the tag into view, clicking on a # tag scrolls you to the top of the current page.

尴尬癌患者 2024-08-24 07:18:48

您在点击事件处理程序中需要使用 return falseevent.preventDefault() 来防止发生默认操作。 href# 元素将导致浏览器视口跳转到页面顶部作为默认操作

return false or event.preventDefault() are what you need in your click event handler to prevent the default action from occurring. An <a> element with a href of # will cause the browser viewport to jump to the top of the page as the default action

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文