[英]Remove keyboard focus from a form element after it goes out of viewport
我如何使用相对较新的Intersection Observer API
来检测当前聚焦的input
何时超出viewport
,以便当它出现时,移除对该input
的关注?
该解决方案应该适用于 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>
在你链接的文档中有一个小提琴你为什么不使用它?
只需将其修改为..
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>
我用你所描述的行为创建了一个 jsfiddle:
var intersectionObserver = new IntersectionObserver(function(entries) {
if (entries[0].intersectionRatio <= 0){
console.log("the field is not visible");
//Add your blur code here
}else{
console.log("the field is visible")
}
});
// start observing
intersectionObserver.observe(document.querySelector('#emailtwo'));
观察者检查intersectionRatio,如果比率<= 0,则表示该元素不在屏幕上。
JSFiddle: https://jsfiddle.net/0f9Lkbgc/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.