html给文本输入框添加自定义的清除按钮

时间:2020-12-28 17:47:27

使用HTML 5,如果对清除按钮的样式不介意的话,可以使用search类型的输入框,它会提供一个默认的清除按钮

<input type="search" placeholder="搜索" />

如果想自定义清除按钮,则需要自己实现,这里使用jquery给出一个实现的方案:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Clear Input Demo</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).ready(function() {
                $('input.clearable').wrap('<span class="clear-box" />')
                                        .after($('<span></span>')
                                        .click(function() {
                    $(this).prev('input').val('').trigger('change').focus();
                }));

            });
        </script>
        <style>
            span.clear-box {
                position: relative;
            }
            span.clear-box span {
                position: absolute;
                display: block;
                top: 4px;
                right: 0px;
                width: 18px;
                height: 18px;
                color: #fff;
                background: #999;
                cursor: pointer;
            }
            span.clear-box span:after{
              position: absolute;
              top: 1px;
              right: 2px;
              content: "\274c";
              font-size: .8em;
            }
            
            span.clear-box input {
                padding-right: 16px;
                box-sizing: border-box;
            }
        </style>
    </head>
    <body>
        <input type="text" class="clearable">
    </body>
</html>