iAoe444 / EveryDay_GitHub

1 stars 0 forks source link

快速获取Mardown格式的网址链接 #12

Open iAoe444 opened 4 years ago

iAoe444 commented 4 years ago

mardown的网址链接格式是New Issue · iAoe444/EveryDay_GitHub,平时要拼接这个好麻烦,我用的firefox没有chrome的插件copytab,所以自己动手丰衣足食,不多说,直接贴代码,使用tampermonkey这个神器就可以了

// ==UserScript==
// @name         复制markdown格式链接
// @namespace    http://iaoe.xyz/
// @version      0.1
// @description  使用ctrl+shift+m键来复制
// @author       iAoe
// @match        http*://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    var title = document.title;
    var url = location.href;      // 获取文档标题和链接
    document.onkeydown = function(e) {      //监听按键按下
        var keyCode = e.keyCode || e.which || e.charCode; 
        var shiftKey = e.shiftKey ;
        var ctrlKey = e.ctrlKey ;
        var content = "["+title+"]"+"("+url+")";
        if(ctrlKey && shiftKey && keyCode == 77) {
            const input = document.createElement('input');
            document.body.appendChild(input);
            input.setAttribute('value', content);
            input.setSelectionRange(0, 9999);
            input.select();
            if (document.execCommand('copy')) {
                document.execCommand('copy');
                console.log('复制成功, 内容:'+content);
            }else{
                console.log('该浏览器不支持此功能');
            }
            document.body.removeChild(input);
            e.preventDefault();
            return false;
        }
    }
})();

使用说明

按住ctrl+shift+m就可以完成复制

代码解剖

  1. 复制到剪贴板 网上看到一些方法,发现不能适配所有的浏览器,于是使用了以下巧妙的方法:

            document.body.appendChild(input);
            input.setAttribute('value', content);
            input.setSelectionRange(0, 9999);
            input.select();
            if (document.execCommand('copy')) {
                document.execCommand('copy');
                console.log('复制成功, 内容:'+content);
            }else{
                console.log('该浏览器不支持此功能');
            }
            document.body.removeChild(input);

    首先使用到了document.execCommand(),这个方法的定义如下

    which allows one to run commands to manipulate the contents of the editable region.

    就是用来控制可编辑区域的内容,所以使用了一个巧妙的方法,创建一个输入框,给输入框放置内容,聚焦到输入框,执行复制命令,删除输入框

  2. 监听按键 监听按键是对document的onekeydown方法的重写

        document.onkeydown = function(e) {
            var keyCode = e.keyCode || e.which || e.charCode;    //对浏览器做了兼容,从而获取keycode
            var altKey = e.altKey ;    //e.altKey和e.shiftKey|ctrlKey|metaKey是功能键,如果这些键按下了,就变成了key
           if(ctrlKey && shiftKey && keyCode == 77) {
                alert("复制成功")
                e.preventDefault();   //阻止默认的按键组合效果
                return false;            //阻止默认的按键组合效果,适配ie
            }
        }

    关于keycode的查询,可以看这篇文章js键盘监听事件_weixin_43608538的博客-CSDN博客,这里的keycode和xmodmap的不一样