离开视口后从表单元素中删除键盘焦点

问题描述 投票:0回答:2

如何使用相对较新的Intersection Observer API来检测当前关注的Intersection Observer API何时不在input之外,以便当它移开时,对viewport的关注会被删除?

该解决方案应可在iOS的Safari中使用。


到目前为止是我的代码:

input
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%
}
javascript ecmascript-6 viewport blur intersection-observer
2个回答
1
投票
只需将其修改为类似..

<main> <section> <form action=submit method=post> <fieldset> <legend>Enter Your Details</legend> <label>Email<br><input type=email name=email [email protected]></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%
}

1
投票
<main> <section> <form action=submit method=post id=myForm> <fieldset> <legend>Enter Your Details</legend> <label>Email<br><input type=email name=email [email protected]></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>

观察者检查相交比率,如果比率<= 0,则表示元素不在屏幕上。

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'));
© www.soinside.com 2019 - 2024. All rights reserved.