Javascript focus() 无需滚动即可输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4963053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:58:50  来源:igfitidea点击:

focus() to input without scrolling

javascripthtmlscroll

提问by NoOneElse

I have a search input text which I'd like to apply a focus()when loading the page, the problem is that the focusfunction automatically does a scroll to this field. Any solution to disable this scroll?

我有一个搜索输入文本,我想focus()在加载页面时应用它,问题是该focus函数会自动滚动到该字段。禁用此滚动的任何解决方案?

<input id="search_terms" type="text" />
<script>
    document.getelementbyId('search-terms').focus();
</script>

采纳答案by peterjwest

Here's a complete solution:

这是一个完整的解决方案:

var cursorFocus = function(elem) {
  var x = window.scrollX, y = window.scrollY;
  elem.focus();
  window.scrollTo(x, y);
}

cursorFocus(document.getElementById('search-terms'));

回答by Josh

There is a new WHATWG standardwhich allows you you to pass an object to focus()which specifies that you want to prevent the browser from scrolling the element into view:

有一个新的WHATWG 标准,它允许您传递一个对象,focus()该对象指定要防止浏览器将元素滚动到视图中:

const element = document.getElementById('search-terms')

element.focus({
  preventScroll: true
});

It has been supported since Chrome 64and Edge Insider Preview build 17046, and should be landing in Firefox 68– a support matrix is available on web-platform-tests here.

它自Chrome 64Edge Insider Preview build 17046起就得到支持,并且应该会登陆Firefox 68- 支持矩阵可在此处的 web-platform-tests 上获得

回答by Felipe Martim

If you are using jQuery, you can also do this:

如果你使用 jQuery,你也可以这样做:

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

and then

进而

$('#search_terms').focusWithoutScrolling();

回答by MDJ

A bit modified version that supports more browsers (incl. IE9)

稍微修改的版本,支持更多浏览器(包括IE9)

var cursorFocus = function(elem) {
  var x, y;
  // More sources for scroll x, y offset.
  if (typeof(window.pageXOffset) !== 'undefined') {
      x = window.pageXOffset;
      y = window.pageYOffset;
  } else if (typeof(window.scrollX) !== 'undefined') {
      x = window.scrollX;
      y = window.scrollY;
  } else if (document.documentElement && typeof(document.documentElement.scrollLeft) !== 'undefined') {
      x = document.documentElement.scrollLeft;
      y = document.documentElement.scrollTop;
  } else {
      x = document.body.scrollLeft;
      y = document.body.scrollTop;
  }

  elem.focus();

  if (typeof x !== 'undefined') {
      // In some cases IE9 does not seem to catch instant scrollTo request.
      setTimeout(function() { window.scrollTo(x, y); }, 100);
  }
}

回答by daniel.gindi

The answers here do not take care of scrolling on the whole hierarchy, but the main scrollbars only. This answer will take care of everything:

此处的答案不考虑在整个层次结构上滚动,而只关注主滚动条。这个答案将处理一切:

    var focusWithoutScrolling = function (el) {
        var scrollHierarchy = [];

        var parent = el.parentNode;
        while (parent) {
            scrollHierarchy.push([parent, parent.scrollLeft, parent.scrollTop]);
            parent = parent.parentNode;
        }

        el.focus();

        scrollHierarchy.forEach(function (item) {
            var el = item[0];

            // Check first to avoid triggering unnecessary `scroll` events

            if (el.scrollLeft != item[1])
                el.scrollLeft = item[1];

            if (el.scrollTop != item[2])
                el.scrollTop = item[2];
        });
    };

回答by tmsss

I had a similar problem that was driving me crazy. Using jQuery, I've found a solution by discovering the coordinates of mouse and input and then scrolling to the difference between them. In your case it could be something like this:

我有一个类似的问题,让我发疯。使用 jQuery,我通过发现鼠标和输入的坐标然后滚动到它们之间的差异找到了一个解决方案。在你的情况下,它可能是这样的:

  document.addEventListener("mousemove", (e) => {
    mouseCoords = { x: e.clientX, y: e.clientY };
  });

  $('#search_terms').bind("focus", function (e) {
      var offset = e.offset();
      window.scrollTo(
        offset.left - mouseCoords.x,
        offset.top - mouseCoords.y
      );
  });

回答by GOTO 0

As of today, the preferred way to set the focus on an element upon page load is using the autofocusattribute. This does not involve any scrolling.

截至今天,在页面加载时将焦点设置在元素上的首选方法是使用autofocus属性。这不涉及任何滚动。

<input id="search_terms" type="text" autofocus />

The autofocusattrubute is part of the HTML5 standardand is supported by all major browsers, with the only notable exception of Internet Explorer 9 or earlier.

autofocusattrubute是HTML5标准的一部分,并通过所有主流浏览器的支持,使用Internet Explorer 9或更早版本的唯一显着的例外。