document ready时Chrome自动填充输入框值无法获取的问题求助
解决Chrome自动填充输入框时无法获取值导致标签样式异常的问题
问题原因
Chrome的自动填充是异步执行的,触发时机晚于$(document).ready()甚至你设置的100ms延时,导致代码检查输入框值时,自动填充还未完成,val()返回空值。此外,Chrome会给自动填充的输入框添加:-webkit-autofill伪类,可利用这一特性辅助判断输入框状态。
解决方案一:使用MutationObserver监听输入框值变化
通过MutationObserver监听输入框的value属性变化,在Chrome自动填充完成时立即更新标签样式:
$(document).ready(function () { // 统一处理标签状态的函数 function updateLabelState($input) { const hasContent = $input.val() !== "" || $input.is(":-webkit-autofill"); if (hasContent || $input.is(":focus")) { $input.prev().addClass("label-top"); } else { $input.prev().removeClass("label-top"); } } // 初始化所有输入框的标签状态 $(".login-form input").each(function() { updateLabelState($(this)); }); // 绑定焦点事件 $(".login-form input") .focus(function () { $(this).prev().addClass("label-top"); }) .blur(function () { updateLabelState($(this)); }); // 监听输入框value属性变化(适配Chrome自动填充) $(".login-form input").each(function() { const observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { if (mutation.type === "attributes" && mutation.attributeName === "value") { updateLabelState($(mutation.target)); } }); }); observer.observe(this, { attributes: true, attributeFilter: ["value"] }); }); });
解决方案二:监听input事件+定时兜底检查
利用input事件捕获所有值变化(包括自动填充),再配合一次延时兜底检查,覆盖极少数延迟填充的情况:
$(document).ready(function () { function updateLabelState($input) { const hasContent = $input.val() !== "" || $input.is(":-webkit-autofill"); $input.prev().toggleClass("label-top", hasContent || $input.is(":focus")); } // 初始化状态 $(".login-form input").each(function() { updateLabelState($(this)); }); // 绑定事件 $(".login-form input") .focus(function () { $(this).prev().addClass("label-top"); }) .blur(function () { updateLabelState($(this)); }) .on("input", function() { updateLabelState($(this)); }); // 兜底检查:处理极晚的自动填充 setTimeout(() => { $(".login-form input").each(function() { updateLabelState($(this)); }); }, 500); });
补充优化:完善输入框属性
原代码中输入框缺少name属性,导致$(document.activeElement).attr("name") != $(this).attr("name")判断失效,建议补充name属性让逻辑更严谨:
<div class="form-group col-12"> <label class="label-top"><span class="px-1">UserName</span></label> <input class="mb-1 col-12 nik-input" type="text" name="username"> <i class="bi bi-person"></i> </div> <div class="form-group col-12"> <label class="label-top"><span class="px-1">Password</span></label> <input class="mb-1 col-12 nik-input" type="password" name="password" value="I AM ALREDY EXIST"> <i class="bi bi-lock"></i> </div>
内容的提问来源于stack exchange,提问作者Saleh
相关产品推荐
相关产品推荐

