焦点()输入而不滚动 [英] focus() to input without scrolling

查看:105
本文介绍了焦点()输入而不滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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


推荐答案

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

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'));

这篇关于焦点()输入而不滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆