javascript - 当表单元素离开视口(viewport)后,将键盘焦点从表单元素上移除

标签 javascript ecmascript-6 viewport blur intersection-observer

如何使用相对较新的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/

相关文章:

javascript - 如何获取没有有效字段的对象?

javascript - 导入未定义时如何出现静态错误

ecmascript-6 - 什么是 () => 运算符?

jquery - Bootstrap模态堆叠删除浏览器滚动条

html - Div 在 iOS 窗口外拉伸(stretch)

javascript - 为什么在页面转换时不调用 next-auth jwt 回调?

javascript - HTML & CSS 视频样式

image - 如何让响应式图片和字幕和谐相处?

Javascript HTML 多时区时钟

javascript - 如何在javascript中将对象转换为字节数组