savsoft,
по мотивам кода от
Malleys
написать текст, сделать выделение, нажать сохранить.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
.selected {
border-radius: 3px;
-webkit-box-decoration-break: clone;
}
::selection {
background: rgba(0, 0, 0, .25);
}
.sel{
border: 1px solid red;
font-size: 1.3em;
}
.show {
display: inline-flex;
flex-direction: column;
}
</style>
<script>
let dataTxt = new Map;
let current;
function styliString(color) {
const textarea = document.querySelector(".txt");
const content = textarea.value.trim();
if(!content) return;
const selection = getSelection();
const range = selection.getRangeAt(0);
const selectionContents = range.extractContents();
const span = document.createElement("span");
const txt = span.cloneNode();
txt.style.backgroundColor = color;
txt.textContent = content;
textarea.value = "";
document.querySelector(".show").append(txt);
for(const oldSpan of selectionContents.querySelectorAll(".selected")) {
for(const childNode of [...oldSpan.childNodes])
oldSpan.parentNode.insertBefore(childNode, oldSpan);
oldSpan.remove();
}
selectionContents.normalize();
span.classList.add("selected");
span.style.backgroundColor = color;
span.appendChild(selectionContents);
range.insertNode(span);
dataTxt.set(span, txt)
}
const randomColor = () => "#" + ('00000' + (Math.random()*(1<<24)|0).toString(16)).slice(-6)
document.addEventListener("click", ({ target }) => {
if(target.classList.contains("save")) {
styliString(randomColor());
}
if(target.classList.contains("selected")) {
const txt = dataTxt.get(target);
if(current && current !== txt) current.classList.remove("sel");
current = txt;
current.classList.toggle("sel")
}
});
</script>
</head>
<body>
<button class="save" >Сохранить</button>
<textarea class="txt" name=""></textarea>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Itaque si aut requietem natura non quaereret aut eam posset alia quadam ratione consequi. Hanc quoque iucunditatem, si vis, transfer in animum; <b>Quod autem ratione actum est, id officium appellamus.</b> Nec vero sum nescius esse utilitatem in historia, non modo voluptatem. An hoc usque quaque, aliter in vita? Quos quidem tibi studiose et diligenter tractandos magnopere censeo. Duo Reges: constructio interrete. Theophrasti igitur, inquit, tibi liber ille placet de beata vita? <i>Eademne, quae restincta siti?</i> Nummus in Croesi divitiis obscuratur, pars est tamen divitiarum. Potius ergo illa dicantur: turpe esse, viri non esse debilitari dolore, frangi, succumbere.</p>
<div class="show"></div>
</body>
</html>