问题
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