Javascript 聚焦大 div 固定 header

Javascript focusing a large div with fixed header

我正在使用一个名为“$.scrollTo”的小型库来为 html 中的 div 元素滚动设置动画。在我的页面顶部,我有一个固定的导航栏。 在动画结束时,我想让 div 集中(为了可访问性)。如果我的 div 太大,在动画结束时,它获得焦点的事实 - 只需将它发送到屏幕外一点。

小 divs 不会发生这种情况。

这是我的代码(检查下面的 jsfiddle):

$('#buttonid').on("click", function() {

//fixed nav bar height (to compensate when scrolling)
var fixed_navbar_height = $("#navbar-id").height();

//the element to scroll to
var $go_to_selector = $("#topic2");

$.scrollTo($go_to_selector, {
  duration: 1000,
  offset: -fixed_navbar_height,
  onAfter: function() {
    //if you comment out this .focus it works as intended.
    $go_to_selector.focus();
  }
});
});

这是一个 JSFIDDLE 示例: https://jsfiddle.net/dy35obpq/3/

显然 onAfter 搞砸了,但我想要动画和焦点。关于如何在不改变滚动条的情况下实现对大 div 的关注的任何想法?非常欢迎提出建议。

试试这个。

  onAfter: function() {
    $go_to_selector.focus();
    $(window).scrollTop($($go_to_selector).offset().top - fixed_navbar_height);
  }

我只是在您的 onAfter 回调中添加了这一行。 $(window).scrollTop($($go_to_selector).offset().top - fixed_navbar_height);

它似乎已经解决了问题,同时仍然保持焦点。您可能想使用 css 禁用焦点蓝色突出显示。