簡體   English   中英

將焦點放在 JS 中的返回元素上

[英]Give focus to returned element in JS

我有一個幻燈片燈箱,當特定的縮略圖圖像獲得焦點並按下“Enter”時,它會被激活。 當我關閉燈箱時,焦點會返回到相同的縮略圖圖像,因此不會打亂標簽順序。 我正在使用全局變量,它工作得很好,但我想盡量不使用全局變量。 這是工作代碼:

let focusedImgBeforeSlideshow

function openSlideshow () {

  *code which opens the slideshow*

  focusedImgBeforeSlideshow = document.activeElement
}


function closeSlideshow () {
  *code which closes the slideshow*

  focusedImgBeforeSlideshow.focus()
}

我嘗試將focusedImgBeforeSlideshow包裝在 function 中,並在openSlideshow()中調用它,如下所示:

function focusedImg () {
  const focusedImgBeforeSlideshow = document.activeElement
  return focusedImgBeforeSlideshow
}

function openSlideshow () {
  focusedImg()
}

...它可以工作,但問題是,當我關閉幻燈片時,我無法返回焦點。 我試過這個:

function closeSlideshow () {
  focusedImg().focus()
}

……但這顯然是胡說八道。 我嘗試過的另一種方法是:

function focusedImg () {
  const focusedImgBeforeSlideshow
  return focusedImgBeforeSlideshow
}

function openSlideshow () {
  let focused = focusedImg ()

  focused = document.activeElement
  
  return focused
}

...但是當我關閉幻燈片時,問題又開始了。

function closeSlideshow () {
  let returnedFocus = openSlideshow ()

  returnedFocus.focused.focus()
}

如何在不使用全局變量的情況下返回焦點?

如果您不想聲明全局變量,可以使用exports關鍵字將代碼包裝到模塊中。

如果您使用 okd javascript (Ecmascript 5),您可以聲明一個IIFE以將您的代碼包裝到 function 中並防止暴露focusedImgBeforeSlideshow變量。

(function() {
  var focusedImgBeforeSlideshow

  window.openSlideshow = function () {
    focusedImgBeforeSlideshow = document.activeElement

    *code which opens the slideshow*
  }

  window.closeSlideshow = function () {
    *code which closes the slideshow*

    focusedImgBeforeSlideshow.focus()
  }

})()

暫無
暫無

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

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