如何防止自动滚动到焦点输入?

Bir*_*sky 3 html javascript css

在某些点击或单击时,我需要将焦点放在视口之外但正在动画中的输入上。但是,由于浏览器如何立即将聚焦元素滚动到视图中,我的转换被搞砸了。

所以简单的问题是,如何防止焦点输入/文本区域元素的自动滚动?

以下是不良行为的示例:

http://jsbin.com/nejiwoy/edit?html,输出

<div
	style="
		position: relative;
		top: 100px;
		left: 100px;
		width: 200px;
		height:100px;
		background: gray;
		overflow: hidden;
	">
	<div
		style="
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			height: 200px;
			background: green;
		">
		<input 
			style="
				position: absolute;
				top: 100px;
				height: 100px;
				width: 100%;
				background: yellow;
				border: none;
			">
	</div>
</div>

<button onclick="document.body.querySelector('input').focus()">focus</button>
Run Code Online (Sandbox Code Playgroud)

Eng*_*eer 6

有一个针对此问题的临时修复 - 已经测试并且可以在最新的 Chrome 中运行。使用

element.focus({ preventScroll: true })

请参阅 GitHub 上的 WHATWG线程