[英]Underline text with line when selected
The idea:想法:
I want to have the text underlined (preferably in a color gradient like here ) when selecting a text section instead of changing the background.在选择文本部分而不是更改背景时,我希望文本带有下划线(最好是像这里这样的颜色渐变)。 According to Mozilla
text-decoration
is possible, so also text-decoration: underline
.根据Mozilla
text-decoration
是可能的,所以也是text-decoration: underline
。
The problem:问题:
( text-decoration
with ::selection
does not work for me (Chrome & Edge) - solved). (带有
::selection
text-decoration
对我不起作用(Chrome 和 Edge) - 已解决)。
The solution idea:解决思路:
Is it at all possible to underline the text as a gradient when making a selection (in CSS)?在进行选择(在 CSS 中)时,是否可以将文本下划线作为渐变? One idea of mine is to use
JavaScript
to see if the text is selected and then add an id="underline"
or so between the text, which then contains the CSS code for the gradient line.我的一个想法是使用
JavaScript
来查看文本是否被选中,然后在文本之间添加一个id="underline"
左右,然后包含渐变线的 CSS 代码。
Progress:进步:
The whole thing is not achieved with pure CSS.整个事情不是用纯 CSS 实现的。 I have now changed the code, so that when a selection is also the text is suitably underlined.
我现在更改了代码,以便在选择也是文本时适当地加下划线。
Problem with the progress:进度问题:
The line remains even after clicking away the selection.即使在单击选择后,该行仍会保留。
The current code:当前代码:
function wrapSelectedText() { var selectedText = window.getSelection().getRangeAt(0); var selection = window.getSelection().getRangeAt(0); var selectedText = selection.extractContents(); var span = document.createElement("span"); /* Styling */ span.style.backgroundImage = "linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%)"; span.style.backgroundRepeat = "no-repeat"; span.style.backgroundSize = "100% 0.2em"; span.style.backgroundPosition = "0 88%"; span.appendChild(selectedText); selection.insertNode(span); } document.onmouseup = document.onkeyup = document.onselectionchange = function() { wrapSelectedText(); };
::selection { background: none; }
<p>This is an example text.</p>
The text-decoration needs to exist already on the element, by defining text-decoration: underline overline transparent;
text-decoration 需要已经存在于元素上,通过定义
text-decoration: underline overline transparent;
on the p
element it does work.在
p
元素上它确实有效。
::selection { background: yellowgreen; /* To check if the text is selected */ text-decoration: underline overline #FF3028; /* Only works on elements that have the same decoration properties set already */ } p { color: black; font-size: 18px; text-decoration: underline overline transparent; }
<p>This is an example text.</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.