输入框中的@如何实现

86 阅读1分钟

记录一下简易Mention实现的代码

样式

 .mention {

      background-color: lightblue;

    }

     .dropdown {

      position: absolute;

      background-color: white;

      border: 1px solid gray;

      padding: 5px;

      z-index: 1;

    }

输入框

  <textarea id="inputText"></textarea>

js

  const inputText = document.getElementById('inputText');

   const mentions = ['Alice', 'Bob', 'Charlie'];

 

    inputText.addEventListener('input', function () {

      const value = this.value;

      const lastChar = value[value.length - 1];

      if (lastChar === '@') {

        const matches = mention`s.filter(mention => mention.startsWith(value.slice(value.lastIndexOf('@') + 1)));

        if (matches.length > 0) {

          const dropdown = document.createElement('div');

          dropdown.classList.add('dropdown');

          matches.forEach(mention => {

            const option = document.createElement('div');

            option.textContent = mention;

            option.addEventListener('click', function () {

              const before = value.slice(0, value.lastIndexOf('@'));

              const after = value.slice(value.lastIndexOf('@') + mention.length);

              inputText.value = before + @${mention} + after;

              document.body.removeChild(dropdown);

            });

            dropdown.appendChild(option);

          });

          document.body.appendChild(dropdown);

 

          const rect = inputText.getBoundingClientRect();

          const cursorPosition = inputText.selectionStart;

          const atPosition = value.lastIndexOf('@');

          const offsetX = rect.left + (cursorPosition - atPosition) * 8;

          const offsetY = rect.top + 20;

          dropdown.style.top = offsetY + 'px';

          dropdown.style.left = offsetX + 'px';

        } else {

          document.body.removeChild(document.querySelector('.dropdown'));

        }

      } else {

        document.body.removeChild(document.querySelector('.dropdown'));

      }

    })