javascript - 如何包装单词看起来像标签?

标签 javascript html css

我想听输入,当用 javascript 单击空格时,空格之前的单词将被换行,看起来像一个标签。

它应该像下面“问一个公共(public)问题”中的“标签”。 到目前为止的代码:

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) 中放什么。 感谢您的帮助。

最佳答案

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

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>

关于javascript - 如何包装单词看起来像标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59564069/

相关文章:

jquery - 如何使用CSS在中间对齐文本?

javascript - 如何将 div 内的内容转换为图像以供社交媒体共享?

html - CSS Mask-image 不起作用

javascript - 使用 html2canvas 的屏幕截图需要在文件夹中另存为 psd

javascript - JQuery 发布未在 PHP 文件中运行代码

php - 照片上传到服务器和数据库的问题

html - 带有变换的样式文本

html - 将 div 堆叠在另一个之上

javascript - Firebase - 动态或更改 orderByChild 变量

javascript - 如何从 Javascript 中读取数据