Skip to content

Instantly share code, notes, and snippets.

@comeontom
Created July 5, 2017 00:52
Show Gist options
  • Save comeontom/ca20729ff7991e9714b512bb8266e4e1 to your computer and use it in GitHub Desktop.
Save comeontom/ca20729ff7991e9714b512bb8266e4e1 to your computer and use it in GitHub Desktop.
浏览器上复制
function select(element) {
var selectedText;
var isReadOnly = element.hasAttribute('readonly');
if (!isReadOnly) {
element.setAttribute('readonly', '');
}
element.select();
element.setSelectionRange(0, element.value.length);
if (!isReadOnly) {
element.removeAttribute('readonly');
}
selectedText = element.value;
return selectedText;
}
function copyText(text) {
var isRTL = document.documentElement.getAttribute('dir') == 'rtl';
var fakeElem = document.createElement('textarea');
// Prevent zooming on iOS
fakeElem.style.fontSize = '12pt';
// Reset box model
fakeElem.style.border = '0';
fakeElem.style.padding = '0';
fakeElem.style.margin = '0';
// Move element out of screen horizontally
fakeElem.style.position = 'absolute';
fakeElem.style[isRTL ? 'right' : 'left'] = '-9999px';
// Move element to the same position vertically
var yPosition = window.pageYOffset || document.documentElement.scrollTop;
fakeElem.style.top = yPosition + 'px';
fakeElem.setAttribute('readonly', '');
fakeElem.value = text;
document.body.appendChild(fakeElem);
select(fakeElem);
var succeeded;
try {
succeeded = document.execCommand('copy');
}
catch (err) {
succeeded = false;
}
if (succeeded) {
alert("复制成功");
} else {
alert("复制失败")
}
}
$(document).ready(function () {
$("div").click(function () {
copyText("click copy");
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment