测试页面上是否存在 div 并将焦点设置到第一个

Test if div exists on page and set focus to first one

我有以下 HTML 仅在出现错误状态时出现:

<div class="validation-summary-errors text-danger">
  <span>Errors:</span>
  <ul>
    <li>Error, please refresh.</li>
  </ul>
</div>

我想将焦点设置到页面下方足够远的 DIV,当用户位于顶部时无法看到它,因此我在页面上尝试了此 jQuery:

  if ($('.validation-summary-errors').length) {
            $('.validation-summary-errors').first().focus();
  }

但是没有用,页面重新加载时焦点仍然在默认位置(页面顶部)。

.focus()不适用于divs:

The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (, , etc.) and links (). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.

http://api.jquery.com/focus/

将焦点置于 div 或部分的最佳方式是滚动到它。您可以使用 jQuery 使用 scrollTop

$('html, body').animate({
   scrollTop: $('yourElementHere').offset().top 
 }, 'slow');