英文:
Javascript - alert problem with onblur and focus-visible Firefox/Chrome
问题
在 onblur
中,我需要调用 alert()
,但在 Chrome 和 Firefox 中不起作用。请参见 https://jsfiddle.net/mimomade/5sur482w/1/。
在 Firefox 中,在离开第2个和第4个输入字段后,:focus-visible
保持不变,不会被移除。
在 Chrome 中,我无法离开第2个输入字段。尽管第1个没有任何问题。
英文:
In onblur
I need to call alert()
, but this doesn't work in Chrome and Firefox. Sess https://jsfiddle.net/mimomade/5sur482w/1/
In Firefox :focus-visible
stays after leaving the 2nd and 4th input field and is not removed.
In Chrome I can't leave the 2nd input field. Although the 1st doesn't has any problem.
答案1
得分: 1
在底部是修复了两个错误的代码。您的初始JavaScript看起来是这样的:
在Firefox中,您的明显错误实际上掩盖了与在Chrome中遇到的类似错误类似的错误。移除警报时,代码会具有预期行为,因此警报和事件会以奇怪的方式进行交互。在这种特定情况下,为了解决这个问题,我们可以通过在零毫秒的超时中包装函数来等待事件完成。
在Chrome中,您的错误似乎是由于在关闭警报框时模糊事件发生引起的。幸运的是,因为我们等待事件完成,所以活动元素应该是新选择的输入元素,而不是浏览器设置的任何元素。这意味着检查确保 el
和 document.activeElement
不同就足以修复这个错误。
英文:
At the very bottom is the code with both bugs fixed. You're initial JavaScript looks like this:
// Has different bugs in Firefox and Chrome.
function blurring(el) {
console.log(el.id + ' pre alert');
alert('blurring ' + el.id);
console.log(el.id + ' post alert');
}
In Firefox, your apparent bug actually masks a bug similar to what you're encountering in Chrome. When the alert is removed, the code has the intended behavior, so alert and the event are interacting in a weird way. In this specific case, to get around this, we can just wait for the event to finish by wrapping the function in a zero-millisecond timeout.
// Has a similar bug in both browsers.
function blurring(el) {
console.log(el.id + ' pre alert');
setTimeout(function () {
alert('blurring ' + el.id);
console.log(el.id + ' post alert');
}, 0);
}
In Chrome, your bug appears to be caused by the blur event emitting each time the alert box is closed. Luckily, because we wait for the events to finish, the active element should be the element newly selected input instead of whatever the browser set it to. This means checking ensuring el
and document.activeElement
are different is sufficient to fix this bug.
// addresses both bugs.
function blurring(el) {
console.log(el.id + ' pre alert');
setTimeout(function () {
if (document.activeElement !== el) {
alert('blurring ' + el.id);
console.log(el.id + ' post alert');
}
}, 0);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论