我正在开发一个允许用户通过标签发布内容的网络应用程序,但问题是,如果标签由 逗号 和文本字段分隔,我将如何在标签周围制作一个漂亮的 block 值仍然相同,只是用户的 View 会有所不同。
例如 YouTube 或 StackOverflow,现在我不需要它来检查数据库或任何东西。
谢谢!
最佳答案
类似 Stack Overflow 的东西:
- 允许字母数字和
+-.#
(并去除空格!) - 转换为小写
- 在 focusOut 上自动创建标签框 Enter ,(添加更多由
|
管道分隔) - 点击删除标签
jQuery($ => { // DOM ready and $ alias in scope.
// TAGS BOX
$("#tags input").on({
focusout() {
var txt = this.value.replace(/[^a-z0-9\+\-\.\#]/ig,''); // allowed characters
if(txt) $("<span/>", {text:txt.toLowerCase(), insertBefore:this});
this.value = "";
},
keyup(ev) {
if(/(,|Enter)/.test(ev.key)) $(this).focusout();
}
});
$("#tags").on("click", "span", function() {
$(this).remove();
});
});
#tags{
float:left;
border:1px solid #ccc;
padding:5px;
font-family:Arial;
}
#tags > span{
cursor:pointer;
display:block;
float:left;
color:#fff;
background:#789;
padding:5px;
padding-right:25px;
margin:4px;
}
#tags > span:hover{
opacity:0.7;
}
#tags > span:after{
position:absolute;
content:"×";
border:1px solid;
padding:2px 5px;
margin-left:3px;
font-size:11px;
}
#tags > input{
background:#eee;
border:0;
margin:4px;
padding:7px;
width:auto;
}
<div id="tags">
<span>php</span>
<span>c++</span>
<span>jquery</span>
<input type="text" value="" placeholder="Add a tag" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
关于javascript - 以逗号分隔的标签的输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14083272/