[英]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.