您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何像iPhone一样在HTML文本输入框中放置一个清除按钮?

如何像iPhone一样在HTML文本输入框中放置一个清除按钮?

@thebluefox总结了全部。您还只需要使用JavaScript即可使该按钮正常工作。这是一个SSCCE,您可以复制’n’粘贴’n’运行它:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 2803532</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).ready(function() {
                $('input.deletable').wrap('<span class="deleteicon" />').after($('<span/>').click(function() {
                    $(this).prev('input').val('').trigger('change').focus();
                }));
            });
        </script>
        <style>
            span.deleteicon {
                position: relative;
            }
            span.deleteicon span {
                position: absolute;
                display: block;
                top: 5px;
                right: 0px;
                width: 16px;
                height: 16px;
                background: url('http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=4') 0 -690px;
                cursor: pointer;
            }
            span.deleteicon input {
                padding-right: 16px;
                @R_822_2419@-sizing: border-@R_822_2419@;
            }
        </style>
    </head>
    <body>
        <input type="text" class="deletable">
    </body>
</html>

jQuery并不是必须的,它只是将渐进增强所需的逻辑与源代码很好地分开了,您当然也可以继续使用纯 HTML / CSS / JS:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 2803532, with "plain" HTML/CSS/JS</title>
        <style>
            span.deleteicon {
                position: relative;
            }
            span.deleteicon span {
                position: absolute;
                display: block;
                top: 5px;
                right: 0px;
                width: 16px;
                height: 16px;
                background: url('http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=4') 0 -690px;
                cursor: pointer;
            }
            span.deleteicon input {
                padding-right: 16px;
                @R_822_2419@-sizing: border-@R_822_2419@;
            }
        </style>
    </head>
    <body>
        <span class="deleteicon">
            <input type="text">
            <span onclick="var input = this.prevIoUsSibling; input.value = ''; input.focus();"></span>
        </span>
    </body>
</html>

您最终只会得到难看的HTML(以及与跨浏览器不兼容的JS;))。

请注意,当用户界面外观不是您最关心的问题,而功能是,则只需使用<input type="search">代替即可<input type="text">。它将在支持HTML5的浏览器上显示(特定于浏览器的)清除按钮。

其他 2022/1/1 18:13:58 有577人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶