gpt4 book ai didi

javascript - 选中时用线为文本下划线

转载 作者:行者123 更新时间:2023-12-04 13:08:11 25 4
gpt4 key购买 nike

想法:
我希望在选择文本部分而不是更改背景时为文本加下划线(最好是颜色渐变 like here )。根据Mozilla text-decoration 是可能的,所以 text-decoration: underline 也是可能的。

问题:
(text-decoration::selection 对我不起作用(Chrome 和 Edge)- 已解决)。

解决思路:
在进行选择时(在 CSS 中)是否可以将文本作为渐变下划线?我的一个想法是使用 JavaScript 来查看文本是否被选中,然后在文本之间添加一个 id="underline" 左右,然后包含 CSS 代码对于渐变线。


进度:
这一切都不是用纯 CSS 实现的。我现在更改了代码,以便在选择的内容也是文本时适本地加下划线。

进度问题:
即使在点击取消选择后,这条线仍然存在。

当前代码:

    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; 它确实有效。

::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>

关于javascript - 选中时用线为文本下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68392935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com