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

如何给W3Schools动画搜索表单添加仅展开后可见的关闭按钮

动画搜索表单添加动态关闭按钮实现方法

修改HTML结构

调整原有表单结构,新增关闭按钮元素:

<form class="search-form">
  <input type="text" class="search-input" name="search" placeholder="Search..">
  <button type="button" class="search-clear" aria-label="清空搜索内容">×</button>
</form>

调整CSS样式

在原有样式基础上新增/修改如下规则,实现关闭按钮默认隐藏、搜索框展开后显示的效果:

/* 表单设置相对定位,作为关闭按钮的定位父级 */
.search-form {
  position: relative;
  display: inline-block;
}

.search-input {
  width: 130px;
  box-sizing: border-box;
  border: 2px solid #ccc;
  border-radius: 4px;
  font-size: 16px;
  background-color: white;
  background-image: url('searchicon.png');
  background-position: 10px 10px; 
  background-repeat: no-repeat;
  padding: 12px 50px 12px 40px; /* 右侧加大内边距,避免输入内容被关闭按钮遮挡 */
  -webkit-transition: width 0.4s ease-in-out;
  transition: width 0.4s ease-in-out;
}

.search-input:focus {
  width: 100%;
}

/* 关闭按钮默认隐藏样式 */
.search-clear {
  display: none;
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  border: none;
  background: none;
  font-size: 18px;
  color: #666;
  cursor: pointer;
  padding: 0;
  opacity: 0;
  transition: opacity 0.3s ease;
}

/* 搜索框聚焦/有输入内容时显示关闭按钮 */
.search-form:focus-within .search-clear,
.search-input:not(:placeholder-shown) + .search-clear {
  display: block;
  opacity: 1;
}

添加交互逻辑

加入JS实现点击关闭按钮的对应功能:

const searchInput = document.querySelector('.search-input');
const clearBtn = document.querySelector('.search-clear');

clearBtn.addEventListener('click', () => {
  searchInput.value = '';
  searchInput.blur(); // 触发失焦让搜索框收回初始宽度,不需要收回可删除此行
});

可选调整说明

  • 如果不需要输入内容失焦后仍保留关闭按钮,删除.search-input:not(:placeholder-shown) + .search-clear这条选择器规则即可
  • 可以自定义修改关闭按钮的字号、颜色等样式匹配整体设计风格

内容的提问来源于stack exchange,提问作者Ucha Buzariashvili

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:39:02