当前位置: 首页 > 知识库问答 >
问题:

javascript - 类@功能如何实现?

唐元凯
2023-04-27

需求:实现一个功能,有多个span标签,内容为用户名,点击span标签,使其以tag的形式出现在一个contentEditable为true的div中,并且tag有背景色和4px的padding,tag不可编辑,当鼠标在div有焦点,则在当前焦点处插入tag,否则将tag加在最后面。

各位有什么实现方案吗

技术:在vue项目中。不要库。原生js实现

共有3个答案

万俟心思
2023-04-27

光标后插入没有实现

<template>
  <div>
    <div class="user-list">
      <span
        v-for="user in userList"
        :data-username="user"
        @click="addTag"
        :key="user"
      >{{ user }}</span>
    </div>
    <div
      id="editor"
      contenteditable="true"
      fouce
    ></div>
  </div>

</template>

<script>
export default {
  data () {
    return {
      userList: ['1', '2', '3', '4']
    }
  },
  methods: {
    addTag (e) {
      const username = e.target.dataset.username;
      const tagElement = document.createElement('tag');
      tagElement.classList.add('tag');
      tagElement.textContent = username;
      tagElement.setAttribute('contenteditable', 'false');
      tagElement.style.backgroundColor = '#eee';
      tagElement.style.padding = '4px';

      const editor = document.getElementById('editor');
      console.log(document.activeElement, editor);
      if (document.activeElement === editor) { // 光标在编辑器内部
        const selection = window.getSelection();
        const range = selection.getRangeAt(0);
        range.deleteContents();
        range.insertNode(tagElement);
        range.collapse(false);
        selection.removeAllRanges();
        selection.addRange(range);
      } else { // 光标不在编辑器内部
        editor.appendChild(tagElement);
      }
    }
  }
}
</script>
<style lang="less" scoped>
.tag {
  display: inline-block;
  margin-right: 4px;
  margin-bottom: 4px;
}
span {
  display: inline-block;
  width: 50px;
  height: 50px;
  background: red;
  margin: 10px;
}
#editor {
  width: 500px;
  height: 500px;
  background-color: aqua;
}
</style>
董弘新
2023-04-27

都说了 contentEditable 肯定是要使用原生 js 的。

不可编辑,整体选中可以改 user-select。

焦点的话就是在前面就提前保存。

 类似资料:
  • 本文向大家介绍javascript如何实现暂停功能,包括了javascript如何实现暂停功能的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了JS实现的自定义网页拖动类。分享给大家供大家参考,具体如下: Javascript本身没有暂停功能(sleep不能使用)同时 vbscript也不能使用doEvents,故编写此函数实现此功能。 javascript作为弱对象语言,一个函数也可以作为

  • 本文向大家介绍javascript中不提供sleep功能如何实现这个功能,包括了javascript中不提供sleep功能如何实现这个功能的使用技巧和注意事项,需要的朋友参考一下 javascript中不提供sleep功能,而我们时长会用到这个功能。 有一种思路是跑一段循环体,让程序空耗CPU的时间来实现延时。这有一个不足,不同的机器CPU的执行速度是不一样的,这很容易导致的慢的机器会SLEEP很

  • 我在读这个答案https://stackoverflow.com/a/1853790/196210我想在我的项目中使用PostSharp,但当我开始阅读他们的许可证时,我真的很失望。 访问属性时,是否有其他方法实现日志记录? http://www.postsharp.net/purchase/faq 如何执行并发许可证? PostSharp定期将使用情况数据上传到我们的服务器,并对这些数据进行分析

  • 以下是我的一个demo,想问问还有没有大神有其他实现方案

  • 问题内容: 我有一个ajax调用,需要返回一个promise。功能如下 在执行下一个动作之前,我必须等待该功能执行。我该如何保证这个功能? 我尝试了以下操作,它给了我一个错误,说: 问题答案: 您有错误,因为它不是Promise。承诺异步功能非常容易(如今,nodejs具有内置的Promise支持):

  • 本文向大家介绍原生JavaScript实现todolist功能,包括了原生JavaScript实现todolist功能的使用技巧和注意事项,需要的朋友参考一下 该项目主要可以练习js操控dom,事件,事件触发之间的逻辑关系,以及如何写入缓存,获取缓存。 主要功能: 将用户输入添加至待办项 可以对todolist进行分类,用户勾选即将待办项分入已完成组 todolist的每一项可删除和编辑 将用户输