CSDN 一键复制

一键复制CSDN代码块

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

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         CSDN 一键复制
// @namespace    http://tampermonkey.net/
// @version      1.0.1
// @description  一键复制CSDN代码块
// @author       Hz
// @match        blog.csdn.net/**
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    var codes = document.getElementsByClassName('prettyprint');
    var timer = null;

    for(var i=0;i<codes.length;i++) {
        var block = codes[i];
        var btn = document.createElement('div');
        btn.style.position = 'absolute';
        btn.style.right = '100px';
        btn.style.top = '4px';
        btn.style.fontSize = '12px';
        btn.style.color = '#4d4d4d';
        btn.style.backgroundColor = 'white';
        btn.style.padding = '2px 8px';
        btn.style.margin = '8px';
        btn.style.borderRadius = '4px';
        btn.style.cursor = 'pointer';
        btn.style.boxShadow = '0 2px 4px rgba(0,0,0,0.05), 0 2px 4px rgba(0,0,0,0.05)';
        btn.innerText = '一键复制';
        block.appendChild(btn);
        btn.onclick = (function(index){
            return function(){
                copyCode(index)
            }
        })(i)
    }

    function copyCode(blockIndex) {
        var str = codes[blockIndex].children[0].innerText;
        var result = false;
        var saveString = function(e){
            e.clipboardData.setData('text/plain', str);
            e.preventDefault();
        }
        document.addEventListener('copy', saveString);
        result = document.execCommand('copy');
        document.removeEventListener('copy', saveString);
        var btn = codes[blockIndex].children[codes[blockIndex].children.length - 1];
        btn.innerText = '已复制';
        if(timer) {
            clearTimeout(timer);
            timer = null;
        }
        timer = setTimeout(function(){
            btn.innerText = '一键复制';
            clearTimeout(timer);
            timer = null;
        }, 3000);
        return result;
    }


    // Your code here...
})();