javascript - 将焦点放在 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()
}
如何在不使用全局变量的情况下返回焦点?
解决方案
如果您不想声明全局变量,可以使用关键字将代码包装到模块中。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()
}
})()
推荐阅读
- go - httputil.NewSingleHostReverseProxy 调用会增加内存使用量
- python-3.x - 从 Tkinter 中的回调函数中检索信息
- python - 创建时将用户设置为组
- swift - 如何获取要正确更新的实体数量
- python - 当键对相同时,将值从一个嵌套字典复制到另一个嵌套字典
- python - 是否可以更改您在 python 中使用的架构?
- javascript - 在不活动时结束 Zopim 聊天
- c# - DataGridView 性能改进
- class - 如何估计一个类的空间复杂度?
- json - ktor 为某些数据类抛出 NoTransformationFoundException