集中焦点在屏幕中央的元素上不起作用。

huangapple go评论69阅读模式
英文:

Put focus on an element on the middle of a screen not working

问题

我有一个检查用户输入是否正确的函数,如果不正确,我希望页面滚动以聚焦在特定的输入字段上。我使用以下代码:

$("#myElementID").focus();

这按预期工作,页面立即跳转到该输入字段并将其放在页面的顶部,没有任何填充。这样很难看,所以我想改为将其聚焦在屏幕中央。我在这个答案中找到了以下代码:

$("#myElementID").focus(function () {
     var center = $(window).height() / 2;
     var top = $(this).offset().top;
     if (top > center) {
         $('html, body').animate({ scrollTop: top - center }, 'fast');            
     }
 });

现在它根本不聚焦,我尝试过alert,似乎根本没有进入这个函数。

如何让输入字段在屏幕中央获得焦点?

英文:

I have a function that checks if user input is correct and if it is not I want the page to scroll to focus on that particular input field. I use the following code:

$("#myElementID").focus();

This works as expected, the page immediately jumps to that input field and puts it right on top of the page without any padding. This makes it hard to see so I want to instead focus it on the center of the screen. I found this answer on SO which shows the following code:

$("#myElementID").focus(function () {
     var center = $(window).height() / 2;
     var top = $(this).offset().top;
     if (top > center) {
         $('html, body').animate({ scrollTop: top - center }, 'fast');            
     }
 });

Now it doesn't focus at all, I tried alert and it doesn't seem to be going into the function at all.

How can I make the input focus centered on screen?

答案1

得分: 1

这段代码将一个处理程序绑定到焦点事件:

$("#myElementID").focus(function(){...});

等效于:

$("#myElementID").on("focus", function(){...});

你应该运行这段代码一次:

$("#myElementID").focus(function () {
     var center = $(window).height() / 2;
     var top = $(this).offset().top;
     if (top > center) {
         $('html, body').animate({ scrollTop: top - center }, 'fast');            
     }
 });

然后使用 $("#myElementID").focus(); 来触发输入字段上的焦点事件。

英文:

This code binds an handler to the focus event :

$("#myElementID").focus(function(){...});

It is equivalent to :

$("#myElementID").on("focus", function(){...});

You are supposed to run this code once :

$("#myElementID").focus(function () {
     var center = $(window).height() / 2;
     var top = $(this).offset().top;
     if (top > center) {
         $('html, body').animate({ scrollTop: top - center }, 'fast');            
     }
 });

And then use $("#myElementID").focus(); to trigger the focus event on your input field.

huangapple
  • 本文由 发表于 2023年2月16日 18:29:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75470930.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定