How to add a tag range to a specific word in a textarea by clicking on that word (if clicked)
P粉561323975
P粉561323975 2023-09-10 13:05:10
0
1
344

When I want to add a label to a word in the text area, the label is not accepted. Is there any way to label text in a textarea by clicking on the word I want to label? For example span tag

<label>
  <textarea class="string-example" name="textarea3" id="textarea3" cols="122" rows="17">Lorem ipsum dolor sit amet...</textarea>
</label>

P粉561323975
P粉561323975

reply all(1)
P粉787820396

Double-click the text in the text area and the text will be highlighted. If you just want to style, use CSS: ::selection

textarea::selection {
  color: white;
  background-color: black;
}

Either use

instead of textarea,
or
Use Textarea as DIV overlay - it will have highlighted tag

.markable {
  display: inline-block;
  position: relative;
}

.markable>* {
  all: unset;
  outline: 1px solid #999;
  vertical-align: top;
  font: 16px/1.4 monospace;
}

.markable div {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  color: transparent;
}

.markable textarea {
  position: relative;
}
Lorem ipsum dolor sit amet...

The above is a proof of concept, you will still need JavaScript to clone text into a .highliter DIV, inserting elements child elements around the desired text selection - and make sure (if necessary) that the underlying DIV scrolls in sync with the text area.

const search = "ipsum";

const regEsc = (str) => str.replace(/[/\-\^$*+?.()|[\]{}]/g, '\$&');

const markable = (elMarkable) => {
  const elDiv = elMarkable.querySelector("div");
  const elTxt = elMarkable.querySelector("textarea");
  const updateScroll = () => {
    elDiv.scrollTop = elTxt.scrollTop;
  };
  const updateMark = () => {
    const val = elTxt.value;
    const markedVal = val.replace(new RegExp(`\b${regEsc(search)}\b`, "gi"), `$&`);
    elDiv.setHTML(markedVal);
  };
  elTxt.addEventListener("scroll", updateScroll);
  elTxt.addEventListener("input", updateScroll);
  elTxt.addEventListener("input", updateMark);
  
  // Init:
  updateScroll();
  updateMark();
};

document.querySelectorAll(".markable").forEach(markable);
.markable {
  display: inline-block;
  position: relative;
}

.markable>* {
  all: unset;
  outline: 1px solid #999;
  vertical-align: top;
  font: 16px/1.4 monospace;
}

.markable div {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  color: transparent;
  overflow: auto;
}

.markable textarea {
  position: relative;
}

Edit the text in textarea below. The string to be highlighted is "ipsum" (case insensitive)

I'll leave the click selection to the reader.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!