jQuery 焦点不滚动
如何将焦点集中到 HTML 元素(例如“a”)而不更改当前的滚动设置。
对于前。如果我使用:
$('#link').focus();
并且此链接在屏幕中不可见(例如位于可见区域下方),则浏览器向下滚动以显示该元素。如何在不移动滚动条的情况下设置焦点?我需要将滚动条保留在原来的位置。
我已经尝试过这个,但它会产生一些屏幕闪烁,这是一个黑客,而不是一个优雅的解决方案:
var st=$(document).scrollTop();
$('#link').focus();
$(document).scrollTop(st);
有人可以帮助我吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这对你来说如此困难的原因是因为你不应该这样做。浏览器旨在帮助用户避免执行此类操作的网站,因为具有焦点的链接将通过按键盘上的回车键或空格键来激活,并且用户很少希望点击他们不知道的链接。
尝试与浏览器合作而不是对抗它,通常会得到更满意的用户。
The reason why this is so hard for you is because you aren't supposed to do it. The browsers are designed to help the user avoid websites that do stuff like this, because a link the has focus will activate by hitting return or space on the keyboard, and users rarely wish to follow a link they are not aware is there.
Try to work with the browser instead of against it, and you will usually end up with happier users.
我有同样的问题,但用语言来说:我认为更优雅的解决方案是在元素位于视口中后给予焦点。
这是我复制/粘贴的内容(从该线程 Jquery 检查是否元素在视口中可见)
I have the same problem, but in words: I think a more elegant solution would be to give the focus once the element is in the viewport.
Here's what I copy/pasted (Kudos to ADB from this thread Jquery check if element is visible in viewport)
尝试这个 jQuery 解决方案:
Try this jQuery solution:
这对我有用
This worked for me
试试这个:
然后
编辑:
据报道这在 IE10 中不起作用。可能的解决方案是使用:
但我还没有测试过。
Try this:
and then
Edit:
It's been reported that this doesn't work in IE10. The probable solution would be to use:
but I haven't tested it.
在 focus 方法上使用
{preventScroll: true}
选项。 https://developer.mozilla.org/en-US/docs /Web/API/HTMLElement/focus如果使用 jQuery,请尝试
$('#el')[0].focus({preventScroll: true})
或迭代集合中的每个元素Use
{preventScroll: true}
option on the focus method. https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focusIf using jQuery try
$('#el')[0].focus({preventScroll: true})
or iterate over each in your collection$('#link').css('position', 'fixed').focus().css('position', 'static')
适用于 Firefox。(编辑:您不应该使用此技巧)
$('#link').css('position', 'fixed').focus().css('position', 'static')
works in Firefox.(Edit: You should not use this hack)