将HTML输入框内的单词转换为可单击按钮

时间:2014-09-10 06:51:31

标签: javascript jquery html css html5

在pinterest.com上,用户可以在搜索框中输入任何内容。只要鼠标离开搜索框,所有单词就会转换为带有关闭按钮的按钮。

同样的事情发生在stackoverflow的'Tags'输入框中。

这是如何实施的?它有一个jquery插件吗?

1 个答案:

答案 0 :(得分:1)

只要找到想要标记行为的关键字: - 更改输入字段的类(这样改变样式 - 使输入字段看起来像一个按钮) - 禁用输入字段 - 显示关闭按钮

HTML代码:

<div class="tag-container">
   <input type="text" class="tag"/>
   <span class="btn-close">&#215;</span>
</div>

CSS代码:

.tag-container{
    position:relative;
    display:inline-block;
}

.tag:focus{
   border-color: blue;
   color: blue;
}

.tag-found .tag{
    background:blue;
    border-color:blue;
    color: white;
}
.btn-close{
    display:none;
}
.tag-found .btn-close{
    display:inline-block;
    color:white;
    background: blue;
    font-size:16px;
    text-align:center;
    position:absolute;
    right:6px;
    top:3px;
    cursor:pointer;
}

Javascript代码:

$(".tag").keyup(function (e) {
    var key = e.which;
    if(key == 13)  // the enter key code
    {
        $(".tag-container").addClass("tag-found");
        $(this).attr("disabled", "disabled");
    }
});

$(".btn-close").click(function(){
    $(".tag-container").removeClass("tag-found");
    $(".tag").removeAttr("disabled");
});

详细了解此示例:http://jsfiddle.net/kwnccc/83qLje4o/