简体   繁体   中英

How do I allow a user to change span textcontent after clicking on the span element?

I am trying to allow the user to click on a span element and change the text according to what they type along with the original textcontent.

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

The textcontent does not seem to update, although the the keydown event listener is working.

Using the contenteditable attribute seems fitting in this case:

 /* Just some styles for this snippet */.targetSpan { background-color: hsla(0, 0%, 50%, 0.15); font-family: sans-serif; font-size: 1.5rem; padding: 0.25rem; }
 <span class="targetSpan" contenteditable="plaintext-only">You can type here</span>


Here's a second example (prompted by this comment ) with a checkbox control for toggling a simulation of plaintext mode:

 const span = document.getElementById('text'); const input = document.querySelector('#toggle'); const setPlaintext = () => { span.textContent = span.textContent; }; const update = () => { if (input.checked) setPlaintext(); }; input.addEventListener('change', update); span.addEventListener('input', update);
 /* Just some styles for this snippet */ body { font-family: sans-serif; } #text { background-color: hsla(0, 0%, 50%, 0.15); font-size: 1.5rem; padding: 0.25rem; }
 <label><input id="toggle" type="checkbox" /> plaintext</label> <span id="text" contenteditable="true">You can type here</span>

I think the recommendation is to use the getElementById() method of document in order to manipulate the contents of a span tag. It seems your code is not using it. Why you may not be getting the results you expect.

There's a few examples for changing the text in a span element in this post How do I change the text of a span element using JavaScript?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM