如何在angular中设置顶部页面的焦点|javascript示例

220 阅读1分钟

考虑一个有长的用户表单和一个支持垂直滚动的提交按钮的页面。当用户按下提交按钮时,服务器会进行验证,任何错误都必须呈现给用户。

如果错误显示在页面的顶部,用户需要滚动到顶部才能看到发生了什么错误。

相反,如果显示错误并将焦点移到页面顶部,在点击按钮时是一个很好的体验。

这篇文章解释了如何在javascript和angular中设置焦点在页面的开始或顶部。

这篇文章解决了一些问题

  • 跳转到浏览器页面的顶部
  • 在点击按钮时强制滚动到页面的顶部
  • 设置焦点到页面顶部
  • 滚动到一个div的顶部 有多种方法可以实现这一点。

使用普通的JavaScript

窗口对象提供了scrollTo函数,可以将光标滚动到页面的坐标处。 ** 语法:** ``javascript window.scrollTo(x-cordinate,y-coridate); (or) window.scrollTo(options)

**parameters:** x-cordinate is the horizontal or x-axis pixel y-coridate is the vertical or y-axis pixel ** Options** is javascript object of type ScrollToOptions - which contains `top`,`left` and `behavior` for example, to move to top of the page. javascript window.scrollTo(0,0); The above can rewritten with shorter form javascript window.scrollTo(0) if you want to add smooth animations, Here is an example javascript window.scrollTo({ top: 0, behavior: 'smooth' }); ```.

假设我们有一个带#jquery的长页面 ``` (document).ready(function(){ (window).scrollTop(0); });

(or)
$(document).scrollTop(0); 


How to move cursor to top of page in typescript


window.scroll({
      top: 0,
      left: 0,
      behavior: 'smooth'
    });


How to set focus to div element on button click submit with javascript?

Usually input elements like textbox, radio and checkboxes has inbuilt focus element.

if you want to  

$('#myform').on('submit', function() {
  $('html, body').animate({scrollTop:0}, 'slow');
});

$('#somecontrolontopofpage')[0].scrollIntoView();