英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论