1+ ( function ( ) {
2+ var snippets = document . querySelectorAll ( 'pre' ) ;
3+ [ ] . forEach . call ( snippets , function ( snippet ) {
4+ snippet . firstChild . insertAdjacentHTML ( 'beforebegin' , '<button type="button" title="复制整段代码到剪切板" class="copy-code-to-clipboard-button" data-clipboard-snippet><i class="far fa-copy"></i></button>' ) ;
5+ } ) ;
6+ var clipboardSnippets = new ClipboardJS ( '[data-clipboard-snippet]' , {
7+ target : function ( trigger ) {
8+ return trigger . nextElementSibling ;
9+ }
10+ } ) ;
11+ clipboardSnippets . on ( 'success' , function ( e ) {
12+ e . clearSelection ( ) ;
13+ showTooltip ( e . trigger , '√' ) ;
14+ } ) ;
15+ clipboardSnippets . on ( 'error' , function ( e ) {
16+ showTooltip ( e . trigger , fallbackMessage ( e . action ) ) ;
17+ } ) ;
18+
19+ var btns = document . querySelectorAll ( '.copy-code-to-clipboard-button' ) ;
20+ for ( var i = 0 ; i < btns . length ; i ++ ) {
21+ btns [ i ] . addEventListener ( 'mouseleave' , clearTooltip ) ;
22+ btns [ i ] . addEventListener ( 'blur' , clearTooltip ) ;
23+ btns [ i ] . addEventListener ( 'mouseenter' , function ( e ) {
24+ showTooltip ( e . currentTarget , "复制?" )
25+ } , false ) ;
26+ }
27+
28+ function clearTooltip ( e ) {
29+ //e.currentTarget.setAttribute('class', 'copy-code-to-clipboard-button');
30+ //e.currentTarget.removeAttribute('aria-label');
31+ }
32+
33+ function showTooltip ( elem , msg ) {
34+ elem . setAttribute ( 'class' , 'copy-code-to-clipboard-button tooltipped tooltipped-s' ) ;
35+ elem . setAttribute ( 'aria-label' , msg ) ;
36+ }
37+
38+ function fallbackMessage ( action ) {
39+ var actionMsg = '' ;
40+ var actionKey = ( action === 'cut' ? 'X' : 'C' ) ;
41+ if ( / i P h o n e | i P a d / i. test ( navigator . userAgent ) ) {
42+ actionMsg = 'No support :(' ;
43+ } else if ( / M a c / i. test ( navigator . userAgent ) ) {
44+ actionMsg = 'Press ⌘-' + actionKey + ' to ' + action ;
45+ } else {
46+ actionMsg = 'Press Ctrl-' + actionKey + ' to ' + action ;
47+ }
48+ return actionMsg ;
49+ }
50+ } ) ( ) ;
0 commit comments