-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodeCopy.js
More file actions
57 lines (56 loc) · 2.14 KB
/
codeCopy.js
File metadata and controls
57 lines (56 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// 代码块一键复制
$(function () {
var $copyIcon = $('<i class="fas fa-copy code_copy" title="复制代码" aria-hidden="true"></i>')
var $notice = $('<div class="codecopy_notice"></div>')
$('.code-area').prepend($copyIcon)
$('.code-area').prepend($notice)
// “复制成功”字出现
function copy(text, ctx) {
if (document.queryCommandSupported && document.queryCommandSupported('copy')) {
try {
document.execCommand('copy') // Security exception may be thrown by some browsers.
$(ctx).prev('.codecopy_notice')
.text("复制成功")
.animate({
opacity: 1,
top: 30
}, 450, function () {
setTimeout(function () {
$(ctx).prev('.codecopy_notice').animate({
opacity: 0,
top: 0
}, 650)
}, 400)
})
} catch (ex) {
$(ctx).prev('.codecopy_notice')
.text("复制失败")
.animate({
opacity: 1,
top: 30
}, 650, function () {
setTimeout(function () {
$(ctx).prev('.codecopy_notice').animate({
opacity: 0,
top: 0
}, 650)
}, 400)
})
return false
}
} else {
$(ctx).prev('.codecopy_notice').text("浏览器不支持复制")
}
}
// 复制
$('.code-area .fa-copy').on('click', function () {
var selection = window.getSelection()
var range = document.createRange()
range.selectNodeContents($(this).siblings('pre').find('code')[0])
selection.removeAllRanges()
selection.addRange(range)
var text = selection.toString()
copy(text, this)
selection.removeAllRanges()
})
});