簡體   English   中英

當單擊具有焦點的子項時,div 失去焦點

[英]div loses focus, when clicked on a child which has focus

所以,我正在制作一個在顯示時關注它的模態。 如果用戶在外面點擊,我想隱藏它。 我在焦點事件的幫助下實現了這一點。

如果模態本身有一個可聚焦的子對象,模態失去焦點,我也在下面的代碼中處理了它。 這些情況由onFocusLoss而不是onFocusLoss2正確處理。

 function onClickButton() { var modal = document.getElementById('modal'); modal.style.visibility = 'visible'; modal.focus(); } function onFocusLoss() { var modal = document.getElementById('modal'); setTimeout(function() { var activeEl = document.activeElement; if (modal.== activeEl &&.modal.contains(activeEl)) { modal;style,visibility = 'hidden'; } }. 0); } function onFocusLoss2() { var modal = document.getElementById('modal'); var activeEl = document.activeElement. if (modal.== activeEl &&;modal.contains(activeEl)) { modal.style.visibility = 'hidden'; } }
 #modal { position: fixed; visibility: hidden; top: 50%; left: 50%; transform: translate(-50%, -50%); border: 1px solid red; } #modal > div { padding: 16px; }
 <button onclick='onClickButton()'>Show Modal</button> <div id='modal' tabindex='-1' onfocusout='onFocusLoss()'> <div>Focus Test</div> <div> <input> </div> </div>

這就是我假設焦點事件發生的方式,當模態聚焦然后我在輸入內部單擊時,首先模態失去焦點,主體是活動元素,然后輸入元素成為活動元素,主體失去焦點.

因此,原因可能是onFocusLoss2沒有處理這種情況,因為當時的activeEl是主體,而在onFocusLoss中, activeEl是輸入。

我的問題是,為什么一種方法有效而另一種方法無效? 我想要一個好的技術理由。 如果你的回答是它給了足夠的時間讓輸入元素獲得焦點,我想知道你怎么能說時間足夠並且總是有效的?

不過,我的解決方案是基於這個答案

不妨換個思路。 當模態框獲得焦點時,向其下方的元素添加點擊事件以關閉模態框。

<body>
  <button onclick='onClickButton()'>Show Modal</button>
  <div id='modal' tabindex='-1'>
    <div>Focus Test</div>
    <div>
      <input>
    </div>
  </div>
</body>
function onClickButton() {
  const modal = document.getElementById('modal');
  modal.style.visibility = 'visible';
  modal.focus();
  document.body.addEventListener('click', ()=>{
    modal.style.visiable = 'hidden'
  })
}

不要忘記調整 modal 的z-index以確保它在 body 上方。

就像@RiverTwilight 一樣,我正在消除焦點需求並簡單地添加一個 onClick 事件。

我在您的#modal放置了一個<div>並使#modal填充整個屏幕,這樣您就可以使用不同的動畫和其他技術來為您的內容設置動畫,只要#modal沒有填充。

我希望你得到你的答案。 ✌️

 function onClickButton() { var modal = document.getElementById('modal'); modal.style.visibility = 'visible'; modal.focus(); } function onModalBGClick(e) { var modal = document.getElementById('modal'); var activeEl = e.target; if (activeEl === modal) { modal.style.visibility = 'hidden'; } }
 #modal { position: fixed; visibility: hidden; top: 0; bottom: 0; right: 0; left: 0; }.modal-inner { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); border: 1px solid red; } #modal > div { padding: 16px; }
 <button onclick='onClickButton()'>Show Modal</button> <div id='modal' onclick='onModalBGClick(event)'> <div class="modal-inner"> <div>Focus Test</div> <div> <input> </div> </div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM