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

如何使用jQuery实现点击自定义图标清空搜索栏输入内容的功能

功能实现步骤

1. 修正原有CSS语法错误

原有CSS存在选择器嵌套错误、重复定义问题,修正后样式可正常生效:

input#wp-search-bar{
    height: 40px;
    width: 807px;
    padding-left: 30px;
    border: 1px solid #ddd;
}
input#wp-search-bar::-webkit-search-cancel-button{ 
    display: none;
}
svg.icon-limpar-search{
    position: relative;
    top: 8px;
    right: 30px;
    cursor: pointer;
}

2. jQuery清空功能实现

确保项目已引入jQuery资源后,添加如下JS代码即可:

$(document).ready(function() {
    // 监听清空图标点击事件
    $('#icon-limpar-search').click(function() {
        // 清空搜索框内容
        $('#wp-search-bar').val('');
        // 清空后自动聚焦搜索框,不需要可直接删除此行
        $('#wp-search-bar').focus();
    });

    // 可选体验优化:无输入内容时隐藏清空图标
    $('#wp-search-bar').on('input propertychange', function() {
        const inputVal = $(this).val().trim();
        $('#icon-limpar-search').toggle(inputVal !== '');
    });
    // 页面初始化时触发一次输入判断,适配搜索框默认带值的场景
    $('#wp-search-bar').trigger('input');
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 18:15:00