如何防止在jQuery中自动滚动到顶部

How do I prevent auto-scrolling to the top in jQuery?

本文关键字:滚动 顶部 何防止 jQuery      更新时间:2023-09-26

这适用于所有其他浏览器,我不知道问题出在哪里。我有点赶时间,所以我想我会问你们,以防我错过了任何明显的东西。我有一个链接,你点击它会启动一个弹出窗口,在Firefox(可能还有opera)中,页面会自动滚动回顶部。

    $('[class*=popup-link]').click(function(e) {
    /* Prevent default actions */
    e.preventDefault();
    e.stopPropagation();
    /* Get the id (the number appended to the end of the classes) */
    var name = $(this).attr('class');
    var id = name[name.length - 1];
    /* Show the correct popup box, show the blackout and disable scrolling */
    $('#popup-box-'+id).show();
    $('#blackout').show();
    $("html,body").css("overflow","hidden");
});

我需要preventDefault和stopPropagation来阻止其他事情的发生。你能看到任何错误或停止自动滚动到顶部的方法吗?谢谢

快速编辑:

我还在运行一个功能,使用将盒子居中

$(window).scroll(centerBox);

我不确定这是否会以某种奇怪的方式影响firefox中的滚动。这个函数的内容只是添加CSS,所以我怀疑它们会对它产生任何影响

另一个编辑:

一个尝试的链接。对我来说,不能在Firefox中工作。http://inserthtml.com/demo/internal-popup/

首先,我在脚本中没有看到任何错误。即使只有CCD_ 1,它也应该防止"顶部跳跃"。试着把它简化为这个。它应该判断这个处理程序是否导致

$('[class*=popup-link]').click(function(e) {
    e.preventDefault();   //prevent the click from jumping esp on hashes
    e.stopPropagation();  //prevent from any parent click handlers that didn't prevent the jump
    //no code here for now
    return false;         //the natural way to prevent the jump
});

如果这段代码阻止了跳转,那么代码的其余部分会导致跳转,尤其是脚本损坏。检查控制台是否也有错误

e.preventDefault();
e.stopPropagation();

相当于

return false;

更改它们,您就可以完成