1. 程式人生 > >js 實現點選複製文字內容

js 實現點選複製文字內容

js  實現點選複製文字內容


 

<table>
    <tr><td>姓名:<span onclick="copyContent(this);" title="點選複製">張 三</span></td></tr>
    <tr><td>姓名:<span onclick="copyContent(this);" title="點選複製">李 四</span></td></tr>
</table>

<
input id="copy_content" type="text" value=""  style="position: absolute;top: 0;left: 0;opacity: 0;z-index: -10;"/> <script type="text/javascript"> function copyContent(ElementObj){ //獲取點選的值 var clickContent = ElementObj.innerText; //獲取要賦值的input的元素 var
inputElement = document.getElementById("copy_content"); //給input框賦值 inputElement.value = clickContent; //選中input框的內容 inputElement.select(); // 執行瀏覽器複製命令 document.execCommand("Copy"); //提示已複製 alter('已複製'); } </script
>

select() 方法只對 <input> 和 <textarea> 有效,所以,要獲取到點選的值,放到input標籤中,再選中複製。