首页 > 解决方案 > 将焦点放在 JS 中的返回元素上

问题描述

我有一个幻灯片灯箱,当特定的缩略图图像获得焦点并按下“Enter”时,它会被激活。当我关闭灯箱时,焦点会返回到相同的缩略图图像,因此不会打乱标签顺序。我正在使用全局变量,它工作得很好,但我想尽量不使用全局变量。这是工作代码:

let focusedImgBeforeSlideshow

function openSlideshow () {

  *code which opens the slideshow*

  focusedImgBeforeSlideshow = document.activeElement
}


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

  focusedImgBeforeSlideshow.focus()
}

我试过包装focusedImgBeforeSlideshow一个函数并像这样调用它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()
}

如何在不使用全局变量的情况下返回焦点?

标签: javascript

解决方案


如果您不想声明全局变量,可以使用关键字将代码包装到模块中。exports

如果您使用的是 okd javascript (Ecmascript 5),您可以声明一个IIFE将您的代码包装到一个函数中并防止暴露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()
  }

})()

推荐阅读