How do I get the previously focused element in JavaScript?

前端 未结 7 1770
死守一世寂寞
死守一世寂寞 2021-01-04 03:46

I have an HTML form with multiple text inputs. I want to clear the element that had the focus immediately prior to when the \'Clear\' button is pressed. How do I ge

7条回答
  •  日久生厌
    2021-01-04 04:07

    The simplest way is to store a reference to document.activeElement within the mousedown event on the button, although this is a mouse-centric approach and won't work for button "clicks" from keyboards and other devices.

    Live demo: http://jsfiddle.net/tEP6w/

    Code:

    var clearButton = document.getElementById("clear");
    var previousActiveElement = null;
    
    clearButton.onmousedown = function() {
        previousActiveElement = document.activeElement;
    };
    
    clearButton.onclick = function() {
        if (previousActiveElement && previousActiveElement != this) {
            previousActiveElement.value = "";
        }
    };
    

    A better approach would be to store a reference to document.activeElement as the button is about to receive the focus. However, this is a little tricky to achieve nicely in all browsers.

提交回复
热议问题