【问题标题】:Underline text with line when selected选中时为文本加下划线
【发布时间】:2021-09-24 07:26:16
【问题描述】:

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

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

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


进展:
整个事情不是用纯 CSS 实现的。 I have now changed the code, so that when a selection is also the text is suitably underlined.

进度问题:
即使在单击选择后,该行仍然存在。

当前代码:

    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>

【问题讨论】:

    标签: javascript html css selection underline


    【解决方案1】:

    文本装饰需要已经存在于元素上,通过在 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
    • @JueK3y 确实因为下划线适用于整个节点,为了实现这一点(以及您想要的任何花哨的自定义样式,如您想要的渐变),您可以使用内联元素包装所选文本(使用 '标记'标签并使用类为其设置样式)。 JS解决方案在以下SO中描述:stackoverflow.com/questions/6328718/…
    猜你喜欢
    • 2015-05-06
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 2014-10-14
    • 2013-08-22
    • 2015-04-19
    相关资源
    最近更新 更多