Greasy Fork

来自缓存

Greasy Fork is available in English.

链接选中

在链接上禁用拖拽行为,左键滑动时选择文本而不是打开链接。

当前为 2025-04-08 提交的版本,查看 最新版本

// ==UserScript==
// @name         链接选中
// @version      0.3
// @namespace    http://greasyfork.icu/users/1171320
// @description  在链接上禁用拖拽行为,左键滑动时选择文本而不是打开链接。
// @author       yzcjd
// @author2     ChatGPT4 辅助
// @match        *://*/*
// @run-at       document-start
// @grant        none
// @license MIT
// ==/UserScript==

(function () {
    'use strict';

    // 🧠 STEP 1: 禁用所有链接的拖拽行为
    const observer = new MutationObserver(() => {
        document.querySelectorAll('a:not([data-nodrag])').forEach(link => {
            link.setAttribute('draggable', 'false');        // 明确禁用拖拽
            link.setAttribute('data-nodrag', '1');          // 防重复处理
        });
    });

    observer.observe(document.body, {
        childList: true,
        subtree: true
    });

    // 🧠 STEP 2: 防止 mousedown 导致拖拽行为,但保留选中
    let isPotentialDrag = false;
    let startX = 0;
    let startY = 0;
    document.addEventListener('mousedown', (e) => {
        if (e.button !== 0) return; // 只处理左键
        const a = findLink(e.target);
        if (a) {
            isPotentialDrag = true;
            startX = e.clientX;
            startY = e.clientY;
        }
    });

    document.addEventListener('mousemove', (e) => {
        if (!isPotentialDrag) return;
        const dx = Math.abs(e.clientX - startX);
        const dy = Math.abs(e.clientY - startY);
        if (dx > 3 || dy > 3) {
            // 👇 模拟文字选择行为,不进行任何干扰
            // 实际上浏览器已经会处理文字选择了
        }
    });

    document.addEventListener('dragstart', (e) => {
        // 🚫 阻止拖拽行为(核心)
        if (findLink(e.target)) {
            e.preventDefault();
        }
    });

    document.addEventListener('mouseup', () => {
        isPotentialDrag = false;
    });

    // 🧠 STEP 3: 覆盖可能禁用用户选中的样式
    const style = document.createElement('style');
    style.textContent = `
        a {
            user-select: text !important;
            -webkit-user-select: text !important;
        }
    `;
    document.head.appendChild(style);

    // 工具:向上查找链接节点
    function findLink(el) {
        while (el && el !== document.body) {
            if (el.tagName === 'A') return el;
            el = el.parentElement;
        }
        return null;
    }
})();