如何使用相对较新的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%
}
<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%
}
<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'));