选中时为文本加下划线
本教程将介绍选中时为文本加下划线的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。
问题描述
创意:
我希望在选择文本部分时将文本加下划线(最好是渐变色like here),而不是更改背景。根据Mozillatext-decoration
是可能的,text-decoration: underline
也是可能的。
问题:
(text-decoration
带::selection
不适用于我(Chrome&;Edge)-已解决)。
解决方案理念:
在进行选择时是否可以将文本加下划线为渐变?我的一个想法是使用JavaScript
查看文本是否被选中,然后在文本之间添加一个id="underline"
,然后包含渐变线的CSS代码。
进度:
整件事不是纯css就能实现的。我现在已经更改了代码,以便当选定内容也是时,文本会适当地加下划线。
进度问题:
即使在取消选择后,该行仍保持不变。
当前代码:
数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
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>
推荐答案
文本装饰需要已存在于元素上,方法是在p
元素上定义text-decoration: underline overline transparent;
它确实起作用。
数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
::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>
好了关于选中时为文本加下划线的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。