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

标签 javascript html css selection underline

想法:
我希望在选择文本部分而不是更改背景时为文本加下划线(最好是颜色渐变 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/

相关文章:

html - normalize.css 和 block 元素的垂直边距

css - Font Awesome 图标不显示

css - 如何检测 Prince PDF 中的分页符?

javascript - 将函数参数传递到 getElementById "id"

javascript - 通过javascript或jquery减少php中的图像文件大小

html - 有什么方法可以在 IE 中下载 HTML5 属性吗?

html - SugarCRM - 传入的电子邮件在正文标签外剥离

javascript - 如何查找以字符串 "word"开头的 cookie 并从带有 char # 的字符串中提取信息

javascript - 使用 moment.js 将天数添加到区域设置特定日期

JavaScript 正则表达式不匹配