首页 > 解决方案 > 如何包装单词以看起来像标签?

问题描述

我想听输入,当用javascript点击空格时,空格之前的单词将被包装成一个标签。

它应该类似于“公开提问”中的“标签”。到目前为止的代码:

html:

<label for="subtypes" id="subtypes_label"><b>Restaurant subtypes</b></label>
<textarea type="text" name="subtypes" class="form-control w-50 p-3" id="subtypes" autocomplete="off" oninput=""></textarea>

javascript:

document.getElementById('subtypes').addEventListener('input', function(evt){
    wrapSubtypes(this.value);
});
function wrapSubtypes(value){

}

不知道往里面放什么wrapSubtypes(value)。谢谢您的帮助。

标签: javascripthtmlcss

解决方案


可能您想从函数中返回一个元素中的包装文本,例如:

return `<span class="tag">${value.trim().split(/\s/).pop()}</span>`  

document.getElementById('subtypes').addEventListener('input', function(evt) {
  if (evt.data === ' ') {
    let tag = wrapSubtypes(this.value);
    document.getElementById('tags').innerHTML += tag;
  }
});

function wrapSubtypes(value) {
  return `<span class="tag">${value.trim().split(/\s/).pop()}</span>`
}
#tags{ padding:10px; }

.tag {
  border-radius: 25%;
  color: #444;
  background: #e5e5e5;
  padding:5px;
  margin-right:10px;
}
<div><label for="subtypes" id="subtypes_label"><b>Restaurant subtypes</b></label>
<textarea type="text" name="subtypes" class="form-control w-50 p-3" id="subtypes" autocomplete="off"></textarea>
</div>

<div id="tags"></div>


推荐阅读