2016-05-27 31 views
4

我想選擇onclick td的innerHTML,以便用戶可以按ctrl + C來複制內容。在點擊時選擇一個TD的值以簡化複製

我嘗試了很多組合,我找不到方法。然而,接縫用一個簡單的document.getElementById(id).select();

上輸入工作添加焦點不影響任何東西,和。選擇()發送和錯誤:

document.getElementById(...).select is not a function

那麼,如何做一個TD元素? 我不介意IE瀏覽器無法正常工作。

或者如果可能,直接複製文本。

+1

http://stackoverflow.com/questions/1173194/select-all-div-text-with-single -mouse-click – user489872

+0

我會使用一個小插件,例如http://timpietrusky.com/_select/ – Djave

+0

@ValentinBEAULE您將問題更改爲與標記的答案匹配? :) – Mohammad

回答

2

複製也並不難。我使用這個功能,這也適用於其他瀏覽器,不只是IE(來源不明)。

https://jsfiddle.net/5bhkydq1/

HTML代碼

<div> 
Click me to copy! 
</div> 

的JavaScript和jQuery

$('div').click(function(){ 
      copyTextToClipboard($(this).html()); 
}); 

function copyTextToClipboard(text) { 
    var textArea = document.createElement("textarea"); 

    // Place in top-left corner of screen regardless of scroll position. 
    textArea.style.position = 'fixed'; 
    textArea.style.top = 0; 
    textArea.style.left = 0; 

    // Ensure it has a small width and height. Setting to 1px/1em 
    // doesn't work as this gives a negative w/h on some browsers. 
    textArea.style.width = '2em'; 
    textArea.style.height = '2em'; 

    // We don't need padding, reducing the size if it does flash render. 
    textArea.style.padding = 0; 

    // Clean up any borders. 
    textArea.style.border = 'none'; 
    textArea.style.outline = 'none'; 
    textArea.style.boxShadow = 'none'; 

    // Avoid flash of white box if rendered for any reason. 
    textArea.style.background = 'transparent'; 


    textArea.value = text; 

    document.body.appendChild(textArea); 

    textArea.select(); 

    try { 
    var successful = document.execCommand('copy'); 
    var msg = successful ? 'successful' : 'unsuccessful'; 
    console.log('Copying text command was ' + msg); 
    } catch (err) { 
    console.log('Oops, unable to copy'); 
    } 

    document.body.removeChild(textArea); 
} 
+0

我標記爲答案,因爲即使它不是我所問的,也完全正常。只是一個問題,爲什麼所有的CSS? –

+0

@ValentinBEAULE你的問題是關於「選擇文本」,而不是「複製文本」。 – Mohammad

+0

關於css: // 1.元素能夠有焦點和選擇。 // 2.如果元素是閃光渲染,它只有最小的視覺衝擊。 // 3.如果 // textarea元素不可見,則選擇和複製時可能會發生**的片狀性較差。 // //可能性是元素甚至不會渲染,甚至沒有閃光, //所以其中一些只是預防措施。然而在IE中,元素 //是可見的,同時彈出框要求用戶許可 //網頁要複製到剪貼板。 –

5

單擊時可以選擇td的文本。

$("td").click(function(){ 
 
    var range = document.createRange(); 
 
    range.selectNodeContents(this); 
 
    var sel = window.getSelection(); 
 
    sel.removeAllRanges(); 
 
    sel.addRange(range); 
 
});
table, tr, td { 
 
    border: 1px solid black; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tr> 
 
     <td>Column1</td> 
 
     <td>Column2</td> 
 
     <td>Column3</td> 
 
    </tr> 
 
    <tr> 
 
     <td>Column1</td> 
 
     <td>Column2</td> 
 
     <td>Column3</td> 
 
    </tr> 
 
</table>

+0

完美,謝謝。 –

相關問題