Focus()不用滚动就可以输入

我有一个搜索输入文本,我想应用一个 focus()当加载页面,问题是 focus函数自动做一个滚动到这个领域。有办法禁用这个卷轴吗?

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

这里有一个完整的解决方案:

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


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

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

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

然后

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

一个稍作修改的版本,支持更多的浏览器(包括 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);
}
}

到目前为止,在页面加载时设置元素焦点的首选方法是使用 autofocus属性。这不涉及任何滚动。

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

The autofocus attrubute is part of the HTML5 standard and is supported by all major browsers, with the only notable exception of Internet Explorer 9 or earlier.

这里的答案并不关心整个层次结构上的滚动,而只关心主滚动条。这个答案会解决一切问题:

    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];
});
};

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

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


element.focus({
preventScroll: true
});

它从 铬64边缘内幕预览版本17046开始就得到了支持,并且应该在 火狐68着陆——在 网站-平台-测试上有一个支持矩阵。

我也有过类似的问题,快把我逼疯了。通过使用 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
);
});