单击#-链接时避免窗口跳转到顶部 [英] Avoid window jump to top when clicking #-links

查看:90
本文介绍了单击#-链接时避免窗口跳转到顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些问题和答案的页面,默认情况下,这些答案已折叠。当他们点击这个问题时,我展开隐藏的答案区。问题是,当我点击这些问题时,窗口跳转到屏幕的顶部。这不是一个大问题,但我觉得很烦人,因为我必须再次向下滚动到问题。



链接看起来像这样:

 < a href =#id =myID> Myquestion< / a> 

我已经使用jQuery和 .click 作为事件监听器。



有没有简单的方法可以避免这种情况,还是我必须使用 .scroll 并找到问题的坐标?我宁愿避免这种情况。编辑:我知道我可以使用锚点来做到这一点,但我想避免任何屏幕跳跃。

解决方案

您需要将 preventDefault()添加到您的点击处理程序中。这将停止浏览器执行它自己的链接处理程序,并且只会运行您指定的代码。


$ b 示例:

<点击(函数(e){
e.preventDefault();
//做你的东西
} pre $ $(#myID );


I've got a page with some questions and answers, the answers are collapsed by default. When they click the question I expand the hidden answer-div. The problem is that when I click these questions, the window jump to the top of the screen. This is not a huge problem, but I find it annoying, because I have to scroll down to the question again.

The links simply looks like this:

<a href="#" id="myID">Myquestion</a>

And I've used jQuery and .click as event-listener.

Are there any simple ways to avoid this, or do I have to use .scroll and finding the coordinates of the question? I'd rather avoid this.

EDIT: I know that I can use anchors to do this, but I'd like to avoid any jumping of the screen at all.

解决方案

You need to add preventDefault() to your click handler. This will stop the browser executing it's own link handler, and will only run the code you specify.

Example:

$("#myID").click(function(e) {
    e.preventDefault();
    // Do your stuff
});

这篇关于单击#-链接时避免窗口跳转到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆