[js] 美化选中文字效果(仿 Microsoft Loop)

image.png

排除了 pdf 界面(因为某些字参差不齐的选区会反复创建卡顿严重)

image.png

(function() {
    // 检查是否已在运行,避免重复注入
    if (window.customSelectionInitialized) {
        return;
    }
    window.customSelectionInitialized = true;

    // 1. 动态注入 CSS (与之前类似,但增加了对 .protyle-wysiwyg 的 position 设置)
    const css = `
        .protyle-wysiwyg {
            position: relative;
        }
        ::selection {
            background-color: transparent!important;
            color: inherit;
        }
        textarea::selection,
        input::selection {
            background-color: var(--b3-theme-primary-lightest, rgba(0, 120, 212, 0.2))!important;
            color: inherit;
        }
        .custom-selection-marker {
            position: absolute;
            width: 2px;
            background-color: var(--b3-theme-primary, #0078d4);
            z-index: 99;
            pointer-events: none;
            opacity: 0;
            transition: opacity 0.15s ease-out;
        }
        .custom-selection-background {
            position: absolute;
            background-color: var(--b3-theme-primary-lightest, rgba(0, 120, 212, 0.2));
            z-index: 98; /* 比光标低一层 */
            pointer-events: none;
        }
    `;
    const styleElement = document.createElement('style');
    styleElement.innerHTML = css;
    document.head.appendChild(styleElement);

    // 2. 创建元素(但不立即附加到 body)
    const startMarker = document.createElement('div');
    startMarker.className = 'custom-selection-marker';

    const endMarker = document.createElement('div');
    endMarker.className = 'custom-selection-marker';

    const backgroundContainer = document.createElement('div');

    // 3. 全局变量,用于跟踪当前选区和其所在的编辑器
    let currentSelection = null;
    let currentEditor = null;

    // 4 & 5. 清除和隐藏函数 (基本不变)
    function clearBackgrounds() {
        backgroundContainer.innerHTML = '';
    }

    function hideAllSelection() {
        clearBackgrounds();
        startMarker.style.opacity = '0';
        endMarker.style.opacity = '0';
        setTimeout(() => {
            if (startMarker.parentElement) {
                startMarker.style.display = 'none';
                endMarker.style.display = 'none';
            }
        }, 150);
    }

    // 6. 更新自定义选区显示的函数 (核心逻辑调整)
    function updateCustomSelection() {
        const selection = window.getSelection();

        if (!selection || selection.isCollapsed || selection.rangeCount === 0) {
            if (currentSelection) {
                hideAllSelection();
                currentSelection = null;
                currentEditor = null;
            }
            return;
        }

        const range = selection.getRangeAt(0);
        const startNode = range.startContainer;
  
        // --- 核心判断:找到选区所在的编辑器 ---
        const editorElement = (startNode.nodeType === Node.TEXT_NODE ? startNode.parentElement : startNode).closest('.protyle-wysiwyg');
  
        // 如果选区不在 .protyle-wysiwyg 内,或者在一些需要原生选区的特殊区域,则隐藏自定义选区
        if (!editorElement || (startNode.parentElement && startNode.parentElement.closest('.pdfViewer,.cm-editor,textarea,input'))) {
            if (currentSelection) {
                hideAllSelection();
                currentSelection = null;
                currentEditor = null;
            }
            return;
        }

        // --- 动态附加/移动元素 ---
        if (currentEditor !== editorElement) {
            currentEditor = editorElement;
            // 将我们的自定义元素附加到新的编辑器中
            currentEditor.appendChild(startMarker);
            currentEditor.appendChild(endMarker);
            currentEditor.appendChild(backgroundContainer);
        }

        clearBackgrounds();

        // 保存当前选区信息
        currentSelection = {
            startContainer: range.startContainer,
            startOffset: range.startOffset,
            endContainer: range.endContainer,
            endOffset: range.endOffset
        };

        renderSelection(range, currentEditor);
    }

    // 7. 渲染选区的函数 (接收 editorElement 作为参数)
    function renderSelection(range, editorElement) {
        if (!editorElement) return;

        const rects = range.getClientRects();
        const editorRect = editorElement.getBoundingClientRect();

        if (rects.length > 0) {
            const startRect = rects[0];
            const endRect = rects[rects.length - 1];

            startMarker.style.display = 'block';
            endMarker.style.display = 'block';

            // 坐标计算 (与上个版本相同)
            startMarker.style.height = `${startRect.height}px`;
            startMarker.style.top = `${startRect.top - editorRect.top + editorElement.scrollTop}px`;
            startMarker.style.left = `${startRect.left - editorRect.left + editorElement.scrollLeft}px`;

            endMarker.style.height = `${endRect.height}px`;
            endMarker.style.top = `${endRect.top - editorRect.top + editorElement.scrollTop}px`;
            endMarker.style.left = `${endRect.right - editorRect.left + editorElement.scrollLeft}px`;

            startMarker.style.opacity = '1';
            endMarker.style.opacity = '1';

            for (const rect of rects) {
                const bgBlock = document.createElement('div');
                bgBlock.className = 'custom-selection-background';
                bgBlock.style.top = `${rect.top - editorRect.top + editorElement.scrollTop}px`;
                bgBlock.style.left = `${rect.left - editorRect.left + editorElement.scrollLeft}px`;
                bgBlock.style.width = `${rect.width}px`;
                bgBlock.style.height = `${rect.height}px`;
                backgroundContainer.appendChild(bgBlock);
            }
        }
    }

    // 8. 重新渲染当前选区的函数
    function refreshSelection() {
        if (!currentSelection || !currentEditor) return;
  
        try {
            const range = document.createRange();
            range.setStart(currentSelection.startContainer, currentSelection.startOffset);
            range.setEnd(currentSelection.endContainer, currentSelection.endOffset);
  
            clearBackgrounds();
            renderSelection(range, currentEditor);
        } catch (e) {
            console.error('刷新选区失败:', e);
            currentSelection = null;
            currentEditor = null;
            hideAllSelection();
        }
    }

    // 9. 监听选区变化
    document.addEventListener('selectionchange', updateCustomSelection);

    // 10. 监听滚动和调整大小事件
    // 注意:这里无法直接监听 currentEditor 的滚动,因为它是动态变化的。
    // 我们采用事件委托的方式,在 document 层面捕获滚动事件。
    let scrollTimeout;
    function handleScrollOrResize(event) {
        if (!currentSelection || !currentEditor) return;
  
        // 检查滚动事件是否发生在当前编辑器或其内部
        if (event.type === 'scroll' && event.target !== document && !currentEditor.contains(event.target)) {
            // 如果滚动的是其他不相关的元素,则忽略
            // return; // 注释掉这行可以简化逻辑,代价是任何滚动都会触发刷新,但性能影响极小
        }
  
        clearTimeout(scrollTimeout);
        scrollTimeout = setTimeout(refreshSelection, 16);
    }

    // 使用 capture: true 可以在事件到达目标前捕获它
    document.addEventListener('scroll', handleScrollOrResize, { passive: true, capture: true });
    window.addEventListener('resize', handleScrollOrResize);

    // 11. 监听页面点击事件
    document.addEventListener('mousedown', () => {
        setTimeout(() => {
            const selection = window.getSelection();
            if (!selection || selection.isCollapsed) {
                if (currentSelection) {
                    currentSelection = null;
                    currentEditor = null;
                    hideAllSelection();
                }
            }
        }, 10);
    });

})();

文科生暂时还没有测试过多行代码选中的卡顿情况,有需要可以测试下

  • 思源笔记

    思源笔记是一款隐私优先的个人知识管理系统,支持完全离线使用,同时也支持端到端加密同步。

    融合块、大纲和双向链接,重构你的思维。

    28444 引用 • 119763 回帖
  • 代码片段

    代码片段分为 CSS 与 JS 两种代码,添加在 [设置 - 外观 - 代码片段] 中,这些代码会在思源笔记加载时自动执行,用于改善笔记的样式或功能。

    用户在该标签下分享代码片段时需在帖子标题前添加 [css] [js] 用于区分代码片段类型。

    285 引用 • 1984 回帖
5 操作
chenshinshi 在 2025-10-27 20:26:45 更新了该帖
chenshinshi 在 2025-10-27 20:23:25 更新了该帖
chenshinshi 在 2025-10-22 15:01:21 更新了该帖
chenshinshi 在 2025-09-25 09:35:09 更新了该帖 chenshinshi 在 2025-09-25 09:26:23 更新了该帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...
  • chenshinshi

    最新版本解决了高亮背景超出界面、滚动页面时不跟随或有延迟、在 input 和 textarea 中无背景的问题。

chenshinshi
前端菜鸟 / 多坑主题搬运工 / 中文系社畜 / 究极妹控 天津

推荐标签 标签

  • Mac

    Mac 是苹果公司自 1984 年起以“Macintosh”开始开发的个人消费型计算机,如:iMac、Mac mini、Macbook Air、Macbook Pro、Macbook、Mac Pro 等计算机。

    168 引用 • 598 回帖
  • Python

    Python 是一种面向对象、直译式电脑编程语言,具有近二十年的发展历史,成熟且稳定。它包含了一组完善而且容易理解的标准库,能够轻松完成很多常见的任务。它的语法简捷和清晰,尽量使用无异义的英语单词,与其它大多数程序设计语言使用大括号不一样,它使用缩进来定义语句块。

    561 引用 • 677 回帖
  • 外包

    有空闲时间是接外包好呢还是学习好呢?

    26 引用 • 234 回帖 • 2 关注
  • ActiveMQ

    ActiveMQ 是 Apache 旗下的一款开源消息总线系统,它完整实现了 JMS 规范,是一个企业级的消息中间件。

    19 引用 • 13 回帖 • 706 关注
  • Outlook
    1 引用 • 5 回帖 • 1 关注
  • 强迫症

    强迫症(OCD)属于焦虑障碍的一种类型,是一组以强迫思维和强迫行为为主要临床表现的神经精神疾病,其特点为有意识的强迫和反强迫并存,一些毫无意义、甚至违背自己意愿的想法或冲动反反复复侵入患者的日常生活。

    15 引用 • 161 回帖 • 1 关注
  • TGIF

    Thank God It's Friday! 感谢老天,总算到星期五啦!

    293 引用 • 4496 回帖 • 688 关注
  • OpenResty

    OpenResty 是一个基于 NGINX 与 Lua 的高性能 Web 平台,其内部集成了大量精良的 Lua 库、第三方模块以及大多数的依赖项。用于方便地搭建能够处理超高并发、扩展性极高的动态 Web 应用、Web 服务和动态网关。

    17 引用 • 51 关注
  • jsDelivr

    jsDelivr 是一个开源的 CDN 服务,可为 npm 包、GitHub 仓库提供免费、快速并且可靠的全球 CDN 加速服务。

    5 引用 • 31 回帖 • 120 关注
  • 游戏

    沉迷游戏伤身,强撸灰飞烟灭。

    188 引用 • 833 回帖 • 2 关注
  • Facebook

    Facebook 是一个联系朋友的社交工具。大家可以通过它和朋友、同事、同学以及周围的人保持互动交流,分享无限上传的图片,发布链接和视频,更可以增进对朋友的了解。

    4 引用 • 15 回帖 • 444 关注
  • Log4j

    Log4j 是 Apache 开源的一款使用广泛的 Java 日志组件。

    20 引用 • 18 回帖 • 60 关注
  • SSL

    SSL(Secure Sockets Layer 安全套接层),及其继任者传输层安全(Transport Layer Security,TLS)是为网络通信提供安全及数据完整性的一种安全协议。TLS 与 SSL 在传输层对网络连接进行加密。

    70 引用 • 193 回帖 • 404 关注
  • WordPress

    WordPress 是一个使用 PHP 语言开发的博客平台,用户可以在支持 PHP 和 MySQL 数据库的服务器上架设自己的博客。也可以把 WordPress 当作一个内容管理系统(CMS)来使用。WordPress 是一个免费的开源项目,在 GNU 通用公共许可证(GPLv2)下授权发布。

    46 引用 • 114 回帖 • 139 关注
  • Linux

    Linux 是一套免费使用和自由传播的类 Unix 操作系统,是一个基于 POSIX 和 Unix 的多用户、多任务、支持多线程和多 CPU 的操作系统。它能运行主要的 Unix 工具软件、应用程序和网络协议,并支持 32 位和 64 位硬件。Linux 继承了 Unix 以网络为核心的设计思想,是一个性能稳定的多用户网络操作系统。

    960 引用 • 946 回帖
  • Unity

    Unity 是由 Unity Technologies 开发的一个让开发者可以轻松创建诸如 2D、3D 多平台的综合型游戏开发工具,是一个全面整合的专业游戏引擎。

    27 引用 • 7 回帖 • 93 关注
  • Office

    Office 现已更名为 Microsoft 365. Microsoft 365 将高级 Office 应用(如 Word、Excel 和 PowerPoint)与 1 TB 的 OneDrive 云存储空间、高级安全性等结合在一起,可帮助你在任何设备上完成操作。

    6 引用 • 35 回帖
  • 小薇

    小薇是一个用 Java 写的 QQ 聊天机器人 Web 服务,可以用于社群互动。

    由于 Smart QQ 从 2019 年 1 月 1 日起停止服务,所以该项目也已经停止维护了!

    35 引用 • 468 回帖 • 768 关注
  • Shell

    Shell 脚本与 Windows/Dos 下的批处理相似,也就是用各类命令预先放入到一个文件中,方便一次性执行的一个程序文件,主要是方便管理员进行设置或者管理用的。但是它比 Windows 下的批处理更强大,比用其他编程程序编辑的程序效率更高,因为它使用了 Linux/Unix 下的命令。

    126 引用 • 83 回帖
  • Bug

    Bug 本意是指臭虫、缺陷、损坏、犯贫、窃听器、小虫等。现在人们把在程序中一些缺陷或问题统称为 bug(漏洞)。

    76 引用 • 1746 回帖 • 10 关注
  • 生活

    生活是指人类生存过程中的各项活动的总和,范畴较广,一般指为幸福的意义而存在。生活实际上是对人生的一种诠释。生活包括人类在社会中与自己息息相关的日常活动和心理影射。

    230 引用 • 1432 回帖
  • MySQL

    MySQL 是一个关系型数据库管理系统,由瑞典 MySQL AB 公司开发,目前属于 Oracle 公司。MySQL 是最流行的关系型数据库管理系统之一。

    695 引用 • 538 回帖 • 2 关注
  • Solo

    Solo 是一款小而美的开源博客系统,专为程序员设计。Solo 有着非常活跃的社区,可将文章作为帖子推送到社区,来自社区的回帖将作为博客评论进行联动(具体细节请浏览 B3log 构思 - 分布式社区网络)。

    这是一种全新的网络社区体验,让热爱记录和分享的你不再感到孤单!

    1449 引用 • 10092 回帖 • 488 关注
  • Jenkins

    Jenkins 是一套开源的持续集成工具。它提供了非常丰富的插件,让构建、部署、自动化集成项目变得简单易用。

    54 引用 • 37 回帖
  • Sandbox

    如果帖子标签含有 Sandbox ,则该帖子会被视为“测试帖”,主要用于测试社区功能,排查 bug 等,该标签下内容不定期进行清理。

    466 引用 • 1241 回帖 • 611 关注
  • 千千插件

    千千块(自定义块 css 和 js)
    可以用 ai 提示词来无限创作思源笔记

    32 引用 • 69 回帖
  • JetBrains

    JetBrains 是一家捷克的软件开发公司,该公司位于捷克的布拉格,并在俄国的圣彼得堡及美国麻州波士顿都设有办公室,该公司最为人所熟知的产品是 Java 编程语言开发撰写时所用的集成开发环境:IntelliJ IDEA

    18 引用 • 54 回帖