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

使用-webkit-search-cancel-button时如何实现清除图标真正按需显示

纯CSS实现方案

利用:placeholder-shown伪类判断输入框是否仍在显示占位符(即用户未输入内容),配合:focus伪类组合判断显示条件,直接控制-webkit-search-cancel-button的显隐,隐藏时不会占用任何页面空间,完全匹配你需要的触发条件:

/* 默认隐藏清除按钮,不占用页面空间 */
input[type="search"]::-webkit-search-cancel-button {
  display: none;
}

/* 仅同时满足「输入框聚焦」+「用户已输入内容(占位符隐藏)」两个条件时显示按钮 */
input[type="search"]:focus:not(:placeholder-shown)::-webkit-search-cancel-button {
  display: block;
}

兼容低版本浏览器的轻量JS方案

如果需要适配不支持:placeholder-shown伪类的旧版浏览器,可以搭配少量JS实现相同效果:

const searchInput = document.querySelector('input[type="search"]')
// 监听输入、聚焦、失焦事件切换按钮显隐
searchInput.addEventListener('input', toggleCancelBtn)
searchInput.addEventListener('focus', toggleCancelBtn)
searchInput.addEventListener('blur', toggleCancelBtn)

function toggleCancelBtn() {
  if (searchInput === document.activeElement && searchInput.value.trim()) {
    searchInput.classList.add('show-cancel')
  } else {
    searchInput.classList.remove('show-cancel')
  }
}

对应的CSS代码:

input[type="search"]::-webkit-search-cancel-button {
  display: none;
}
input[type="search"].show-cancel::-webkit-search-cancel-button {
  display: block;
}

内容的提问来源于stack exchange,提问作者Denis Kulagin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:27:03