没有滚动的jQuery焦点

buz*_*zlo 32 jquery scroll focus scrollbar

如何关注HTML元素(例如"a")并且不要更改当前的滚动设置.

对于前者 如果我使用:

$('#link').focus();
Run Code Online (Sandbox Code Playgroud)

并且此链接在屏幕中不可见(例如,在可见区域下方),浏览器向下滚动以显示元素.如何在没有滚动条移动的情况下设置焦点?我需要在原始位置保留滚动条.

我试过这个,但它会产生一些屏幕闪烁,这是一个黑客,而不是一个优雅的解决方案:

var st=$(document).scrollTop();
$('#link').focus();
$(document).scrollTop(st);
Run Code Online (Sandbox Code Playgroud)

请问有人可以帮助我吗?

Fel*_*tim 44

试试这个:

$.fn.focusWithoutScrolling = function(){
  var x = window.scrollX, y = window.scrollY;
  this.focus();
  window.scrollTo(x, y);
  return this; //chainability

};
Run Code Online (Sandbox Code Playgroud)

然后

$('#link').focusWithoutScrolling();
Run Code Online (Sandbox Code Playgroud)

编辑:

据报道,这在IE10中不起作用.可能的解决方案是使用:

var x = $(document).scrollLeft(), y = $(document).scrollTop();
Run Code Online (Sandbox Code Playgroud)

但我没有测试过它.

  • 不要忘记归还这个; 关闭功能之前...如果你喜欢链接. (4认同)

Dan*_*ell 6

使用{preventScroll: true}焦点方法的选项。 https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus

如果使用 jQuery 尝试$('#el')[0].focus({preventScroll: true})或迭代您集合中的每个


jd.*_*jd. 3

$('#link').css('position', 'fixed').focus().css('position', 'static')在 Firefox 中工作。

编辑:你不应该使用这个黑客)