滚动后到达视口时如何自动将焦点设置在 <input> 字段上?
How to automatically set focus on a <input> field when it arrives in the viewport after scrolling?
我知道 autofocus
属性:
<input type="email" id="hello" placeholder="a@b.com" autofocus>
自动将焦点设置在 HTML 输入上。
但是当页面远高于浏览器高度时,有没有办法(有一个特殊值autofocus
?)只有当滚动后<input>
到达视口/页面当前可见部分?
function handleScroll() {
var el = document.getElementById('hello')
var rect = el.getBoundingClientRect();
var elemTop = rect.top;
var elemBottom = rect.bottom;
// Only completely visible elements return true:
var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
// Partially visible elements return true:
//isVisible = elemTop < window.innerHeight && elemBottom >= 0;
if (isVisible) el.focus();
}
<body onscroll="handleScroll()" style="overflow: scroll;">
<input id="hello" type="email" placeholder="a@b.com" style="margin-top: 500px; margin-bottom: 200px;" />
</body>
我知道 autofocus
属性:
<input type="email" id="hello" placeholder="a@b.com" autofocus>
自动将焦点设置在 HTML 输入上。
但是当页面远高于浏览器高度时,有没有办法(有一个特殊值autofocus
?)只有当滚动后<input>
到达视口/页面当前可见部分?
function handleScroll() {
var el = document.getElementById('hello')
var rect = el.getBoundingClientRect();
var elemTop = rect.top;
var elemBottom = rect.bottom;
// Only completely visible elements return true:
var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
// Partially visible elements return true:
//isVisible = elemTop < window.innerHeight && elemBottom >= 0;
if (isVisible) el.focus();
}
<body onscroll="handleScroll()" style="overflow: scroll;">
<input id="hello" type="email" placeholder="a@b.com" style="margin-top: 500px; margin-bottom: 200px;" />
</body>