选中时为文本加下划线 [英] Underline text with line when selected

查看:33
本文介绍了选中时为文本加下划线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创意:
我希望在选择文本部分时将文本加下划线(最好是渐变色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>

这篇关于选中时为文本加下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆