油猴脚本
// ==UserScript==
// @name Copy Selected Text Button
// @namespace http://tampermonkey.net/
// @version 3
// @description Add a copy button to selected text on a webpage to easily copy the selected text to clipboard
// @match *://*/*
// @exclude https://www.yihan.it/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
// create a copy button
var copyBtn = document.createElement('button');
copyBtn.id = 'copyBtn';
copyBtn.style.display = 'none';
copyBtn.style.position = 'fixed';
copyBtn.style.zIndex = '9999';
copyBtn.style.top = '0';
copyBtn.style.right = '0';
copyBtn.style.margin = '3px';
copyBtn.style.padding = '5px';
copyBtn.style.border = 'none';
copyBtn.style.borderRadius = '3px';
copyBtn.style.background = '#000';
copyBtn.style.color = '#fff';
copyBtn.style.fontSize = '7px';
copyBtn.style.cursor = 'pointer';
copyBtn.innerText = '复制';
copyBtn.style.boxShadow = '2px 2px 5px rgba(0, 0, 0, 0.3)';
// add copy button to document body
document.body.appendChild(copyBtn);
// add event listener to document body
document.addEventListener('mouseup', function(e) {
var selection = window.getSelection().toString().trim();
if (selection !== '' && !e.target.matches('input[type="text"], textarea')) {
copyBtn.style.display = 'block';
copyBtn.style.left = e.clientX - copyBtn.offsetWidth + 30 + 'px';
copyBtn.style.top = e.clientY - copyBtn.offsetHeight + 'px';
copyBtn.addEventListener('click', function() {
navigator.clipboard.writeText(selection);
copyBtn.style.display = 'none';
});
} else {
copyBtn.style.display = 'none';
}
});
})();
适用于网页控制台
(function() {
'use strict';
// create a copy button
var copyBtn = document.createElement('button');
copyBtn.id = 'copyBtn';
copyBtn.style.display = 'none';
copyBtn.style.position = 'fixed';
copyBtn.style.zIndex = '9999';
copyBtn.style.top = '1000';
copyBtn.style.right = '1000';
copyBtn.style.margin = '3px';
copyBtn.style.padding = '5px';
copyBtn.style.paddingLeft = '8px';
copyBtn.style.paddingRight = '8px';
copyBtn.style.border = 'none';
copyBtn.style.borderRadius = '3px';
copyBtn.style.background = '#000';
copyBtn.style.color = '#fff';
copyBtn.style.fontSize = '7px';
copyBtn.style.cursor = 'pointer';
copyBtn.innerText = '复制';
copyBtn.style.boxShadow = '2px 2px 5px rgba(0, 0, 0, 0.3)';
// add copy button to document body
document.body.appendChild(copyBtn);
// add event listener to document body
document.body.addEventListener('mouseup', function(e) {
var selection = window.getSelection().toString().trim();
if (selection !== '') {
copyBtn.style.display = 'block';
copyBtn.style.left = e.clientX - copyBtn.offsetWidth - 10 + 'px';
copyBtn.style.top = e.clientY - copyBtn.offsetHeight + 'px';
copyBtn.addEventListener('click', function() {
navigator.clipboard.writeText(selection);
copyBtn.style.display = 'none';
});
} else {
copyBtn.style.display = 'none';
}
});
})();