javascript 检索先前聚焦的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3639908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:48:22  来源:igfitidea点击:

Retrieving previously focused element

javascript

提问by Mick

I would like to find out, in Javascript, which previous element had focus as opposed to the current focus. I've been looking through the DOM and haven't found what I need, yet. Is there a way to do this any help would be much appreciated

我想在 Javascript 中找出哪个先前的元素具有焦点而不是当前焦点。我一直在浏览 DOM,但还没有找到我需要的东西。有没有办法做到这一点,任何帮助将不胜感激

回答by Peter Ajtai

Each time an element is focused, you'd have to store which one it was. Then when another element is focused, you could retrieve the variable for the previous focused element.

每次聚焦一个元素时,您都必须存储它是哪一个。然后,当另一个元素获得焦点时,您可以检索前一个焦点元素的变量。

So basically, your singlefocus handler would do 2 things:

所以基本上,你的焦点处理程序会做两件事

  1. Check if previousFocus is defined. If it is, retrieve it.
  2. Set previousFocus to the currently focused element.
  1. 检查是否定义了 previousFocus。如果是,请检索它。
  2. 将 previousFocus 设置为当前聚焦的元素。

Here is a quick demo with jQuery (you can use raw JS too... just fewer lines w jQuery, so it's easier to understand imo):

这是一个使用 jQuery 的快速演示(您也可以使用原始 JS ……使用 jQuery 的行数更少,因此更容易理解 imo):

  // create an anonymous function that we call immediately
  // this will hold our previous focus variable, so we don't
  // clutter the global scope
(function() {

      // the variable to hold the previously focused element
    var prevFocus;

      // our single focus event handler
    $("input").focus(function() {

          // let's check if the previous focus has already been defined
        if (typeof prevFocus  !== "undefined") {

              // we do something with the previously focused element
            $("#prev").html(prevFocus.val());
        }

          // AFTER we check upon the previously focused element
          //   we (re)define the previously focused element
          //   for use in the next focus event
        prevFocus = $(this);
    });
})();

working jsFiddle

工作 jsFiddle

回答by Gone Coding

Just found this question while solving the exact same problem and realised it was so old the jQuery world has moved on a bit :)

刚刚在解决完全相同的问题时发现了这个问题,并意识到它太老了,jQuery 世界已经向前发展了一点:)

This should provide a more effective version of Peter Ajtais code, as it will use only a single delegated event handler (not one per input element).

这应该提供更有效的Peter Ajtais 代码版本,因为它将只使用一个委托的事件处理程序(而不是每个输入元素一个)。

// prime with empty jQuery object
window.prevFocus = $();

// Catch any bubbling focusin events (focus does not bubble)
$(document).on('focusin', ':input', function () {

    // Test: Show the previous value/text so we know it works!
    $("#prev").html(prevFocus.val() || prevFocus.text());

    // Save the previously clicked value for later
    window.prevFocus = $(this);
});

JSFiddle:http://jsfiddle.net/TrueBlueAussie/EzPfK/80/

JSFiddle:http : //jsfiddle.net/TrueBlueAussie/EzPfK/80/

Notes:

笔记:

  • Uses $() to create an empty jQuery object (allows it to be used immediately).
  • As this one uses the jQuery :inputselector it works with select& buttonelements as well as inputs.
  • It does not need a DOM ready handler as documentis always present.
  • As the previously focused control is required "elsehere" is is simply stored on windowfor global use, so it does not need an IIFE function wrapper.
  • 使用 $() 创建一个空的 jQuery 对象(允许立即使用它)。
  • 由于这个使用 jQuery:input选择器,它可以与select&button元素以及输入一起使用。
  • 它不需要document总是存在的 DOM 就绪处理程序。
  • 由于需要先前聚焦的控件,因此“其他地方”只是存储在window供全局使用,因此它不需要 IIFE 函数包装器。

回答by Pointy

Well depending on what else your page is doing, it could be tricky, but for starters you could have a "blur" event handler attached to the <body>element that just stashes the event target.

好吧,取决于您的页面正在做什么,这可能很棘手,但对于初学者来说,您可以将“模糊”事件处理程序附加到<body>仅隐藏事件目标的元素上。

回答by mike rodent

To me this seems a slight improvement on Gone Coding's answer:

对我来说,这似乎对 Gone Coding 的回答略有改进:

window.currFocus = document;
// Catch focusin 
$(window).on( 'focusin', function () {
  window.prevFocus = window.currFocus;
  console.log( '£ prevFocus set to:');
  console.log( window.currFocus );
  window.currFocus = document.activeElement;
});

... there's no stipulation in the question that we're talking exclusively about INPUTs here: it says "previous elements". The above code would also include recording focus of things like BUTTONs, or anything capable of getting focus.

...我们在INPUT这里只讨论s的问题中没有任何规定:它说“以前的元素”。上面的代码还包括记录诸如BUTTONs之类的东西的焦点,或者任何能够获得焦点的东西。

回答by John Hascall

Here is a slightly different approach which watches both focusinand focusout, in this case to prevent focus to a class of inputs:

这是一种稍微不同的方法,它同时监视focusinfocusout,在这种情况下是为了防止将注意力集中在一类输入上:

<input type="text" name="xyz" value="abc" readonly class="nofocus">
<script>
$(function() {
        var leaving = $(document);
        $(document).on('focusout', function(e) {
                leaving = e.target;
        });
        $( '.nofocus' ).on('focusin', function(e) {
                leaving.focus();
        });
        $( '.nofocus' ).attr('tabIndex', -1);
});
</script>

Setting tabIndexprevents keyboard users from "getting stuck".

设置tabIndex可防止键盘用户“卡住”。

回答by Juri Sinitson

document.getElementById('message-text-area').addEventListener('focus',
  event => console.log('FOCUS!')
);

event.relatedTargethas all the data about the previously focused element.

event.relatedTarget拥有有关先前关注的元素的所有数据。

See also https://developer.mozilla.org/en-US/docs/Web/API/Event/Comparison_of_Event_Targets

另见https://developer.mozilla.org/en-US/docs/Web/API/Event/Comparison_of_Event_Targets