You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS :focus伪类在移动端及Google Chrome中失效问题排查

问题分析与解决方案

我来帮你搞定这个Chrome下的CSS失效问题~

问题根源

你的CSS规则其实已经覆盖了两种场景:#quantity聚焦时显示相邻input,以及相邻input自身聚焦时保持显示。但Chrome的焦点事件处理逻辑和Firefox不一样:
当你点击那个原本是display:none的input时,事件顺序是先让#quantity失去焦点——这时候第一个CSS选择器失效,input立刻变回隐藏状态;而因为它已经不在文档流里了,Chrome没法触发它的focus事件,第二个选择器自然也不生效,导致它一直藏着。Firefox在处理隐藏元素的点击/focus时逻辑更宽松,所以能正常工作。

解决方案

给你两种靠谱的处理方式:

方案1:纯CSS修改(最简单)

把相邻input的默认隐藏方式从display:none改成visibility:hidden或者opacity:0,让它保持在文档流里,这样点击时能正常触发焦点:

/* 默认状态 */
input[type='text']#quantity + input {
  visibility: hidden;
  position: absolute;
  top: 0;
  left: 0;
  width: 50px;
}

/* 聚焦时显示 */
input[type='text']#quantity:focus + input, 
input[type='text']#quantity + input:focus {
  visibility: visible;
}

如果喜欢用透明度效果,把visibility换成opacity:0和opacity:1就行,逻辑是一样的。

方案2:JS辅助控制(更灵活)

通过监听焦点事件,用类来控制显示,避开CSS选择器的局限性:

const quantityInput = document.getElementById('quantity');
const targetInput = quantityInput.nextElementSibling;

// quantity聚焦时显示目标input
quantityInput.addEventListener('focus', () => {
  targetInput.classList.add('show');
});

// quantity失焦时,延迟检查目标input是否聚焦,没聚焦就隐藏
quantityInput.addEventListener('blur', () => {
  setTimeout(() => {
    if (!targetInput.matches(':focus')) {
      targetInput.classList.remove('show');
    }
  }, 10);
});

// 目标input失焦时隐藏
targetInput.addEventListener('blur', () => {
  targetInput.classList.remove('show');
});

对应的CSS:

input[type='text']#quantity + input {
  display: none;
  position: absolute;
  top: 0;
  left: 0;
  width: 50px;
}

input[type='text']#quantity + input.show {
  display: block !important;
}

这里加setTimeout是为了给焦点切换留一点点时间,确保能准确判断目标input是否拿到了焦点。

内容的提问来源于stack exchange,提问作者N.A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:50:32