当前位置:首页 > JavaScript

js实现标签盒子

2026-03-15 15:45:37JavaScript

实现标签盒子的基本思路

标签盒子通常用于展示多个标签,允许用户添加、删除或选择标签。以下是一个简单的实现方法:

<div id="tag-container">
  <input type="text" id="tag-input" placeholder="输入标签...">
  <button id="add-tag">添加</button>
  <div id="tags"></div>
</div>
#tag-container {
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 5px;
  max-width: 300px;
}

#tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-top: 10px;
}

.tag {
  background-color: #e0e0e0;
  padding: 3px 8px;
  border-radius: 3px;
  display: inline-flex;
  align-items: center;
}

.tag-remove {
  margin-left: 5px;
  cursor: pointer;
}
document.getElementById('add-tag').addEventListener('click', function() {
  const input = document.getElementById('tag-input');
  const tagText = input.value.trim();

  if (tagText) {
    addTag(tagText);
    input.value = '';
  }
});

function addTag(text) {
  const tagsContainer = document.getElementById('tags');
  const tag = document.createElement('div');
  tag.className = 'tag';

  const span = document.createElement('span');
  span.textContent = text;

  const removeBtn = document.createElement('span');
  removeBtn.className = 'tag-remove';
  removeBtn.textContent = '×';
  removeBtn.addEventListener('click', function() {
    tag.remove();
  });

  tag.appendChild(span);
  tag.appendChild(removeBtn);
  tagsContainer.appendChild(tag);
}

支持回车键添加标签

为提升用户体验,可以增加回车键添加标签的功能:

js实现标签盒子

document.getElementById('tag-input').addEventListener('keypress', function(e) {
  if (e.key === 'Enter') {
    document.getElementById('add-tag').click();
  }
});

标签去重功能

防止添加重复标签:

function addTag(text) {
  const existingTags = Array.from(document.querySelectorAll('.tag span'))
    .map(span => span.textContent);

  if (existingTags.includes(text)) {
    alert('标签已存在');
    return;
  }

  // 原有添加标签的代码...
}

获取已添加标签的数据

需要获取当前所有标签时:

js实现标签盒子

function getTags() {
  return Array.from(document.querySelectorAll('.tag span'))
    .map(span => span.textContent);
}

响应式标签盒子

使用现代前端框架如React的实现示例:

function TagBox() {
  const [tags, setTags] = useState([]);
  const [inputValue, setInputValue] = useState('');

  const handleAddTag = () => {
    const trimmed = inputValue.trim();
    if (trimmed && !tags.includes(trimmed)) {
      setTags([...tags, trimmed]);
      setInputValue('');
    }
  };

  const handleRemoveTag = (tagToRemove) => {
    setTags(tags.filter(tag => tag !== tagToRemove));
  };

  return (
    <div className="tag-container">
      <input
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
        onKeyPress={(e) => e.key === 'Enter' && handleAddTag()}
      />
      <button onClick={handleAddTag}>添加</button>
      <div className="tags">
        {tags.map(tag => (
          <div key={tag} className="tag">
            <span>{tag}</span>
            <span className="tag-remove" onClick={() => handleRemoveTag(tag)}>×</span>
          </div>
        ))}
      </div>
    </div>
  );
}

可编辑标签功能

实现双击标签编辑的功能:

function makeTagEditable(tagElement) {
  const span = tagElement.querySelector('span');
  const originalText = span.textContent;

  span.contentEditable = true;
  span.focus();

  const handleBlur = () => {
    span.contentEditable = false;
    const newText = span.textContent.trim();
    span.textContent = newText || originalText;
    span.removeEventListener('blur', handleBlur);
  };

  span.addEventListener('blur', handleBlur);
}

// 在addTag函数中为标签添加双击事件
tag.addEventListener('dblclick', function() {
  makeTagEditable(this);
});

这些方法提供了从基础到进阶的标签盒子实现方案,可以根据具体需求进行调整和扩展。

标签: 盒子标签
分享给朋友:

相关文章

vue实现标签

vue实现标签

Vue 实现标签功能的方法 在 Vue 中实现标签功能可以通过多种方式,以下是几种常见的方法: 使用动态组件和 v-for 指令 通过 v-for 循环渲染标签列表,结合动态组件或条件渲染实现标签内…

vue实现盒子平移

vue实现盒子平移

Vue 实现盒子平移的方法 使用 CSS Transition 和 v-bind:style 通过 Vue 的 v-bind:style 动态绑定 CSS 样式,结合 transition 实现平滑的…

vue实现标签打印

vue实现标签打印

Vue 实现标签打印 在 Vue 中实现标签打印通常需要结合浏览器的打印功能和 CSS 控制打印样式。以下是几种常见的方法: 使用 window.print() 方法 创建一个专门用于打印的组件或页…

vue实现标签切换

vue实现标签切换

实现标签切换的方法 在Vue中实现标签切换功能,可以通过动态组件或条件渲染来实现。以下是几种常见的方法: 使用v-if和v-show指令 通过v-if或v-show指令控制不同标签内容的显示与隐藏。…

vue 实现tag标签

vue 实现tag标签

Vue 实现 Tag 标签 在 Vue 中实现 Tag 标签可以通过多种方式完成,以下是几种常见的实现方法。 使用原生 HTML 和 CSS 通过 Vue 的模板语法结合 CSS 样式可以快速实现基…

vue标签实现跳转

vue标签实现跳转

vue-router 实现页面跳转 在 Vue 项目中通常使用 vue-router 进行路由跳转管理,以下是常见的实现方式: 声明式导航 <router-link to="/path"&g…