How to use relatedTarget across browsers?

余生颓废 提交于 2020-01-05 05:35:29

问题


Firefox supports relatedTarget for the focus/blur but not the focusin/focusout event.

IE supports it only for the focusin/focusout but not the focus/blur event.

Chrome supports both.

Is there a way to use relatedTarget across browsers?

Here is a blur example (working in Chrome and FF but not IE): https://jsfiddle.net/rnyqy78m/

And here a focusin example (working in Chrome and IE but not FF): https://jsfiddle.net/rnyqy78m/1/

Edit

I ended up using browser detection. So I use

var eventType;
if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
    eventType = 'blur';
} else {
    eventType = 'focusout';
}

and then ….addEventListener(eventType, …).


回答1:


(Posting as an answer so I can use code sample. Although this is more meant to be a comment.)

There's alot of duplicates of this question on SO, just no answers that work 100% of the time. Then again, this problem doesn't come up that often once you get to large/complex apps. If I need the order a user manipulated stuff in, I just save it as a variable.

So my code would just reverse the logic and use 'focus' instead of blur if you need it to work for the first focus as well. If the blur event also needs to happen if the user doesn't click another input event, I would also bind the focus event handler to any click event on the page. This kind of strategy would be crossbrowser, it's just not pretty and/or efficient.

This isn't perfect, since it will trigger two events after the first click, but that can be solved easily. But with playign around with the code a bit, it should be possible to find a combination of events that mimic the behaviour needed. (So I'd need more details on when the console element should get the id written or not to write anm exact implementation.)

<!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
</head>
<body>
    <input id="one" value="focus me first">
    <input id="two" value="focus me next">
    <input id="console">
    <script>
    var currentElement,
        inputOne = document.getElementById('one'),
        inputTwo = document.getElementById('two'),
        inputConsole = document.getElementById('console'),
        focusHandler = function( event ) {
            if (currentElement) inputConsole.value += currentElement.id;
            currentElement = event.target;
        };
    inputOne.addEventListener('focus', focusHandler);
    inputTwo.addEventListener('focus', focusHandler);
    // optional handler for 'focus non-input elements', aka blur the prev clicked element.
    document.addEventListener('click', focusHandler);
    </script>
</body>
</html>


来源:https://stackoverflow.com/questions/41299372/how-to-use-relatedtarget-across-browsers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!