gpt4 book ai didi

javascript - jQuery .on 模糊函数在 Firefox 中执行不正确

转载 作者:行者123 更新时间:2023-11-30 05:30:45 25 4
gpt4 key购买 nike

客户想要一种表单,其中输入的数字在某些方面表现得像 Excel。特别是,保存的数据和显示的数据可能不同,就像在 Excel 中一样。例如,保存的数据可能是 32425.537342,显示的数据可能是 $32,425.54

我们采用的方法是使用输入对,type='text'之一和type='number'。默认情况下隐藏的number input 存储要发送的数据,text input 显示它给用户。 number input 只有在相应的text input 被聚焦时才会显示,此时这样的text 输入 是隐藏的。

以下代码在 Chrome 中的行为符合预期。

HTML:

<input type="text">
<input type="number">
<br>
<input type="text">
<input type="number">

jQuery:

$(document).ready(function(){
$("[type='number']").hide();
$("[type='text']").on("focus",function(){
$(this).next().show().focus();
$(this).hide();
});
$("[type='number']").on('blur',function(){
$(this).prev().show();
$(this).hide();
});
});

Fiddle .但是,在适用于 Mac OS 的 Firefox(版本 33.1.1)中,完全不起作用。当 text input 被聚焦时,它会完全消失,而 number input 永远不会显示。

为了确定问题出在哪里,我将代码缩减为:

$(document).ready(function(){
$("[type='number']").hide();
$("[type='text']").on("focus",function(){
$(this).next().show().focus();
$(this).hide();
});
});

Fiddle .这实际上在 Chrome 和 Firefox 中都按预期工作;在焦点上,text input 永久隐藏,number input 永久显示。

看来问题出在代码的后半部分。如果你去掉 $(this).hide();,代码在 Chrome 和 Firefox 中的行为一致(尽管不是特别有用的方式):

$(document).ready(function(){
$("[type='number']").hide();
$("[type='text']").on("focus",function(){
$(this).next().show().focus();
$(this).hide();
});
$("[type='number']").on('blur',function(){
$(this).prev().show();
/* $(this).hide(); */
});
});

Fiddle .同样,如果您仅删除 $(this).prev().show();,它在 Chrome 和 Firefox 中的行为也相同:所有内容最终都会隐藏。

$(document).ready(function(){
$("[type='number']").hide();
$("[type='text']").on("focus",function(){
$(this).next().show().focus();
$(this).hide();
});
$("[type='number']").on('blur',function(){
/* $(this).prev().show(); */
$(this).hide();
});
});

Fiddle .只有当两条线都在那里时才会出现行为上的分歧; Chrome 隐藏一个 input 并显示另一个,而 Firefox 会在您专注于 text input 时立即让所有内容消失。

我认为这可能与 Firefox 焦点/模糊问题有关,该问题使其在 iframe 中表现异常(example),但将其从 JSFiddle 的 iframe 中移除没有任何效果。全屏 fiddle here .

那么如何使 Firefox 中的行为与 Chrome 中的行为相匹配呢?

最佳答案

This answer提供了可以解决问题的 JavaScript,并使用它我能够在 jQuery 中组合等效项:

$(document).ready(function(){
$('[type="number"]').hide();
$('[type="text"]').on('focus',function(){
$(this).next().show().focus();
$(this).hide();
});
$('[type="number"]').on('blur',function(){
var $this = $(this);
setTimeout(function() {
if(!$(document.activeElement).is($this)){
$($this).hide();
$($this).prev().show();
}
}, 0);
});
});

Fiddle .

引自that answer至于为什么这是必要的:

[T]he issue is that different browsers choose to call event handlers in different orders. One solution is to give the other events a chance to fire by setting a timer for 0 milliseconds, and then checking the fields to see which (if any) is focused.

关于javascript - jQuery .on 模糊函数在 Firefox 中执行不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27198316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com