jQuery focus without scroll

2019-01-17 06:26发布

How can I focus to a HTML element (ex. "a") and do not change the current scroll settings.

For ex. if I use:

$('#link').focus();

and this link is not visible in the screen (ex. is bellow the visible area) the browser scrolls down to show the element. How can I set the focus without scrollbar movement? I need to stay the scrollbar in the original place.

I have tried this, but it produces some screen flickering, and it is a hack, not an elegant solution:

var st=$(document).scrollTop();
$('#link').focus();
$(document).scrollTop(st);

Can somebody help me, please?

7条回答
混吃等死
2楼-- · 2019-01-17 07:04

Use {preventScroll: true} option on the focus method. https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus

If using jQuery try $('#el')[0].focus({preventScroll: true}) or iterate over each in your collection

查看更多
登录 后发表回答