javascript - 使用 jQuery 确定页面 anchor (#) 访问何时发生

标签 javascript jquery html css

当用户使用 jQuery 单击特定链接并将它们滚动到页面上的 anchor 时,我目前正在拦截。页面滚动到 anchor 后,我想显示一个 div 并关注该 div 中的一个元素。以下代码执行此操作但存在问题...

// Intercept the click on the link which scrolls to the signup form
$('#section-footer-buttons a').click(function(){
    // Scroll to the welcome section
    location.href = '#welcome';

    // Show the hidden signup form if it's not already visible
    $('#signup-form').slideDown(350, function(){
        // Focus on the first element on the form now the animation is complete
        $('#signup-form :input:enabled:visible:first').focus();
    });

    // We've handled this click so return false
        return false;
});

问题是当页面向上滚动到注册表单所在的 anchor 时,隐藏的 div 已经可见,没有漂亮的 slideDown 动画。有没有办法只在页面停止滚动后才开始 slideDown 动画?本质上,我需要从 location.href 完成时的回调。

最佳答案

你应该换一种方式。

$('#section-footer-buttons a').click(function(){
    var welcome = '#welcome',
        $offset = $('[href="'+welcome+'"]').offset().top;

    $('html,body').animate({
        scrollTop:$offset,350
    },function(){
        location.href = welcome;

        $('#signup-form').slideDown(350, function(){
            $(this).find('input').filter(':enabled:visible').first().focus();
        });
    });

    return false;
});

像这样使用 .animate() 回调函数应该能为您提供所需的东西。

关于javascript - 使用 jQuery 确定页面 anchor (#) 访问何时发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23143994/

相关文章:

html - CSS nth-child 所有元素显示为 "odd"

html - 似乎无法使用 css 获得正确的布局

javascript - 表单数据和 "select multiple"

javascript - AJAX、JSON、PHP 联系表单、event.preventDefault 不起作用且数据未发送到电子邮件

javascript - 通过引用或复制导入 ES6 变量

jquery - 拖动 Draggable 时添加 Droppable

javascript - AJAX - 使用 AJAX 将 knockout 可观察值作为 JSON 对象发送到服务器

javascript - 为什么三元运算符中不能有 return ?

java - jlabel 中的格式化文本和导入的值

javascript - 用于社交提供商的 Firebase 身份验证事件的云功能