當我想為文字區域中的單字添加標籤時,該標籤不被接受。有什麼方法可以透過點擊我要新增標籤的單字來為文字區域中的文字加上標籤嗎? 例如span標籤
<label> <textarea class="string-example" name="textarea3" id="textarea3" cols="122" rows="17">Lorem ipsum dolor sit amet...</textarea> </label>
P粉7878203962023-09-11 10:39:22
雙擊文本區域中的文本,該文本將突出顯示。如果您只想設定樣式,請使用 CSS: ::selection
textarea::selection { color: white; background-color: black; }
<textarea>Lorem ipsum dolor sit amet, consectetur adipisicing elit ipsum. Eaque, facere architecto. Ipsum quas, modi impedit veritatis earum sunt quo reiciendis. Hic, sapiente earum fuga accusamus qui eos itaque provident! Eaque, ipsum in.</textarea>
要嘛使用 以上是概念證明,您仍然需要JavaScript 才能將文字複製到 我將把點擊選擇留給讀者。
或
使用 Textarea 作為 DIV 覆蓋層 - 它將具有突出顯示的標記
.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;
}
<div class="markable">
<div>Lorem <mark>ipsum</mark> dolor sit amet...</div>
<textarea>Lorem ipsum dolor sit amet...</textarea>
</div>
.highliter
DIV 中,插入 元素子元素圍繞所需的文字
選擇
- 並確保(如果需要)底層DIV 與文字區域同步滾動。 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"), `<mark>$&</mark>`);
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;
}
<p>Edit the text in textarea below. The string to be highlighted is "ipsum" (case insensitive)</p>
<div class="markable">
<div></div>
<textarea name="textarea3" cols="40" rows="2">Lorem ipsum dolor sit amet, consectetur adipisicing elit ipsum. Eaque, facere architecto. Ipsum quas, modi impedit veritatis earum sunt quo reiciendis. Hic, sapiente earum fuga accusamus qui eos itaque provident! Eaque, ipsum in.</textarea>
</div>