如何使用相对较新的Intersection Observer API
检测当前聚焦的输入
何时超出视口(viewport)
,以便当它超出输入
时,该输入
的焦点被移除?
该解决方案应该适用于 iOS 版 Safari。
<小时/>这是迄今为止我的代码:
document.addEventListener("DOMContentLoaded", _ => {
const focusedInput = document.activeElement
// ?
focusedInput.blur()
})
html { height: 100% }
html, body, main, section {
display: flex;
flex-grow: 1
}
main { flex-direction: column }
section {
justify-content: center;
align-items: center;
flex: 1 0 100%
}
<main>
<section>
<form action=submit method=post>
<fieldset>
<legend>Enter Your Details</legend>
<label>Email<br><input type=email name=email placeholder=jane@example.com></label><hr>
<label>Message<br><textarea name=briefing placeholder="Lorem ipsum dolor sit amet."></textarea></label><hr>
<input type=submit value=Submit>
</fieldset>
</form>
</section>
<section>
<h2>Second Page</h2>
</section>
</main>
最佳答案
在您链接的文档中有一个 fiddle 为什么不使用它?
只需将其修改为类似..
document.addEventListener("DOMContentLoaded", _ => {
let observerOptions = {
root: null,
rootMargin: "0px",
threshold: [0, 0.1, 0.99]
};
let intersectionCallback = (entries) => {
entries.forEach((entry) => {
if (entry.intersectionRatio == 0) { // fully invisible
//document.activeElement.blur()
}
if (entry.intersectionRatio < 1) { // partially invisible
document.activeElement.blur()
}
});
}
let observer = new IntersectionObserver(intersectionCallback, observerOptions);
observer.observe(document.querySelector("#myForm"));
})
html { height: 100% }
html, body, main, section {
display: flex;
flex-grow: 1
}
main { flex-direction: column }
section {
justify-content: center;
align-items: center;
flex: 1 0 100%
}
<main>
<section>
<form action=submit method=post id=myForm>
<fieldset>
<legend>Enter Your Details</legend>
<label>Email<br><input type=email name=email placeholder=jane@example.com></label><hr>
<label>Message<br><textarea name=briefing placeholder="Lorem ipsum dolor sit amet."></textarea></label><hr>
<input type=submit value=Submit>
</fieldset>
</form>
</section>
<section>
<h2>Second Page</h2>
</section>
</main>
关于javascript - 当表单元素离开视口(viewport)后,将键盘焦点从表单元素上移除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58930688/