gpt4 book ai didi

javascript - 创建标签框

转载 作者:行者123 更新时间:2023-11-28 01:06:36 25 4
gpt4 key购买 nike

我正在制作一个类似于 StackOverflow 的标签框。我看到这里已经有人问过这个问题 ( How to make a "tags box" using jQuery (with text input field + tags separated by comma) ),但我有一个关于 Javascript 的问题。

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='tag-container' id = "tag-container">
<span class='dashfolio-tag'>Tag1</span>
<span class='dashfolio-tag'>Tag2</span>
<span class='dashfolio-tag'>Tag3</span>
</div>


<input type="text" value="" placeholder="Add a tag" id = "add-tag-input" />

CSS:

.tag-container {
max-width: 300px; /* helps wrap the tags in a specific width */

}

.dashfolio-tag {
cursor:pointer;
background-color: blue;
padding: 5px 10px 5px 10px;
display: inline-block;
margin-top: 3px; /*incase tags go in next line, will space */
color:#fff;
background:#789;
padding-right: 20px; /* adds space inside the tags for the 'x' button */
}

.dashfolio-tag:hover{
opacity:0.7;
}

.dashfolio-tag:after {

position:absolute;
content:"×";
padding:2px 2px;
margin-left:2px;
font-size:11px;
}

#add-tag-input {
background:#eee;
border:0;
margin:6px 6px 6px 0px ; /* t r b l */
padding:5px;
width:auto;
}

JS:

$(document).ready(function(){
$(function(){

$("#add-tag-input").on({
focusout : function() {
var txt = this.value.replace(/[^a-z0-9\+\-\.\#]/ig,''); // allowed characters
if(txt) $("<span/>", {text:txt.toLowerCase(), insertBefore:this});


this.value = "";
},
keyup : function(ev) {
// if: comma|enter (delimit more keyCodes with | pipe)
if(/(188|13)/.test(ev.which)) $(this).focusout();
}
});
$('.tag-container').on('click', 'span', function() {
if(confirm("Remove "+ $(this).text() +"?")) $(this).remove();
});

});

});

我的问题很简单,如何在 #tag-container 中添加新输入作为带有类 dashfolio-tag 的范围?我尝试使用 insertBefore 属性尝试将其添加到正确的节点,但无济于事。提前谢谢大家!

最佳答案

改变这行代码,

if(txt) $("<span/>", {text:txt.toLowerCase(), insertBefore:this});

if(txt) {
$("<span/>", {
text:txt.toLowerCase(),
appendTo:"#tag-container",
class:"dashfolio-tag"
});
}

查看演示:https://jsfiddle.net/2gvdsvos/4/


固定标签之间的边距,

将 HTML 更新为,

<div>
<div class="tag-container" id="tag-container">
<span class='dashfolio-tag'>tag1</span>
<span class='dashfolio-tag'>tag2</span>
<span class='dashfolio-tag'>tag3</span>
</div>
</div>
<div>
<input type="text" value="" placeholder="Add a tag" id="add-tag-input" />
</div>

并将其添加到 CSS,

.tag-container:after {
visibility: hidden;
display: block;
font-size: 0;
content: " ";
clear: both;
height: 0;
}

.dashfolio-tag {
...
margin-right: 4px;
float: left;
}

希望对您有所帮助! ;)

https://jsfiddle.net/2gvdsvos/5/

关于javascript - 创建标签框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39482063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com