【问题标题】:How do I allow a user to change span textcontent after clicking on the span element?单击跨度元素后如何允许用户更改跨度文本内容?
【发布时间】:2023-01-07 03:15:10
【问题描述】:

我正在尝试允许用户单击 span 元素并根据他们键入的内容以及原始文本内容更改文本。

container.addEventListener('click', (event) => {
   if (event.target.classList.contains('targetSpan')){
                targetSpanText = event.target.textContent;
                document.addEventListener("keydown", (event) => {
                    targetSpanText.textContent += `${event.key}`;
                });
            }
        });

textcontent 似乎没有更新,尽管 keydown 事件侦听器正在工作。

【问题讨论】:

    标签: javascript html class events text


    【解决方案1】:

    在这种情况下使用 contenteditable attribute 似乎很合适:

    // For browsers which don't support the "plaintext-only" value:
    document.querySelector('span.targetSpan').addEventListener('input', (ev) => {
      ev.currentTarget.textContent = ev.currentTarget.textContent;
    });
    <span class="targetSpan" contenteditable="plaintext-only">You can type here</span>

    【讨论】:

      猜你喜欢
      • 2013-06-28
      • 1970-01-01
      • 2019-05-11
      • 2020-02-09
      • 1970-01-01
      • 2018-01-21
      • 1970-01-01
      • 2021-12-20
      • 2019-07-01
      相关资源
      最近更新 更多