【问题标题】:Using jQuery confirm and scrollTop causing page to scroll up then back down使用 jQuery 确认和 scrollTop 导致页面向上滚动然后向下滚动
【发布时间】:2019-08-05 15:10:27
【问题描述】:

我在一个项目中使用 jQuery-confirm 库,当与 jQuery 动画结合使用时,页面会滚动到顶部,然后再向下滚动到底部。代码如下:

$.alert({
    boxWidth: '50%',
    useBootstrap: false,
    title: '<p>Questionnaire Errors Found</p>',
    titleClass: 'alert_title',
    content: "<p class='alert_body'>Errors were found in the submitted questionaire and are highlighted in red\n\nPlease review and correct the missing information</p>",
    buttons:    {
        okay:   {
            text: 'Okay',
            btnClass: 'alert_button',
            action: function()  {

                $('html').animate({
                    scrollTop: $('#voters_guide_form').offset().top
                        }, 500);

                    }
                }
            }
        });

如果我不使用确认库,则行为会按预期工作。同样不使用动画也不会使页面滚动。我尝试在动画中使用 html,body 没有任何变化,并且我已经将动画代码移入和移出警报代码,但它仍然做同样的事情。

浏览了他们的文档和互联网,我似乎找不到这样的东西。

【问题讨论】:

    标签: javascript jquery jquery-ui jquery-plugins


    【解决方案1】:

    您应该使用$('body') 而不是$('html')

    Answer source

    因此您需要将代码更改为:

    $.alert({
        boxWidth: '50%',
        useBootstrap: false,
        title: '<p>Questionnaire Errors Found</p>',
        titleClass: 'alert_title',
        content: "<p class='alert_body'>Errors were found in the submitted questionaire and are highlighted in red\n\nPlease review and correct the missing information</p>",
        buttons:    {
            okay:   {
                text: 'Okay',
                btnClass: 'alert_button',
                action: function()  {
                     //Changed to body and added stop
                    $('body').stop().animate({
                        scrollTop: $('#voters_guide_form').offset().top
                            }, 500);
                        }
                    }
                }
            });
    

    此外,在运行新动画之前停止在body 中运行的动画是一个很好的做法。这就是我添加stop() 方法的原因。

    请注意:如果您通过 iframe 导入此代码,它将不起作用,因为使用 iframe,您的页面现在将有 2 个(或更多)正文,$('body') 应该返回一个数组而不是一个对象。

    【讨论】:

    • 不,当我将其更改为正文时(无论是否停止调用,它都不会向上滚动到页面顶部,只是“坐在那里”
    • 嗯..奇怪...你不是从其他地方加载脚本吗?像 jQuery.load() 或类似的东西?
    • 不确定加载是什么意思。整个事情都在一个验证表单的函数中,当然,在 document.ready() 中
    • 您的 document.ready() (顺便说一下它的 $(document).ready())是在 内还是从 js 文件加载,甚至是从 HTML 加载文件?这就是我要问的
    • 另外,您是否尝试过添加回调函数来制作动画?它会被触发吗? animate 的构造函数(complete 是回调) - animate(properties, duration, easing, complete)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-29
    相关资源
    最近更新 更多