如何留在jQuery点击后的当前宽度/高度?

问题描述:

当我点击下面的代码时,页面向上移动。我怎样才能保持当前的宽度/高度,而不是在页面的开头移动用户?如何留在jQuery点击后的当前宽度/高度?

<script type="text/javascript"> 
    $(document).ready(function() { 
     $("#click").click(function() { 
    //some things in here 
     }); 
    }); 
</script> 

导航到顶部是这样的链接的默认行为,并且可以通过调用e.preventDefault(),其中e是jQuery的事件参数来防止:

$("#click").click(function(e) { // <-- `e` is passed to the function 
    e.preventDefault(); 

    //some things in here 
}); 

如果#click是锚定元件, <a id="click" href=""></a>,那么你会得到页面顶部的行为。因此,请执行@pimvdb建议的或使用不同的元素(如spandiv)。

您可以使用e.preventDefault()或只返回false,返回false包含preventDefault()并且还可以防止事件冒泡。

$("#click").click(function() { 
    // something here 
    return false 
});