2017-02-08 52 views
1

那麼,當我在網上搜索一些基本的代碼來檢查 - 我發現了這一個。一個簡單的代碼,應該複製選定的文本。由於我是JS中的一名完全新手,我檢查了我不明白的方法的含義,並重新編寫了代碼,因爲我做了一些調整。創建一個「複製按鈕」

仍然代碼不工作,如果有人可以解釋 - 這部分「」copyit(this.form.select1)「」 - 即使我有點理解「這個」 - 我無法理解什麼是doind這裏

function copyit(theField) { 
var selectedText = document.getSelection(); 
if (selectedText.type == 'Text') { 
    var newRange = selectedText.createRange(); 
    theField.focus(); 
    theField.value = newRange.text; 
} else { 
    alert('select a text in the page and then press this button'); 
} 
} 
</script> 



<form name="it"> 
<div align="center"> 
<input onclick="copyit(this.form.select1)" type="button" value="Press to copy the highlighted text" name="btnCopy"> 
<p> 
<textarea name="select1" rows="4" cols="45"></textarea> 
</div> 
</form> 

這是原來的代碼 - 它不工作要麼

<SCRIPT LANGUAGE="JavaScript"> 
function copyit(theField) { 
var selectedText = document.selection; 
if (selectedText.type == 'Text') { 
    var newRange = selectedText.createRange(); 
    theField.focus(); 
    theField.value = newRange.text; 
} else { 
    alert('select a text in the page and then press this button'); 
} 
} 
</script> 


And in the body of your web page, add the following where you want the text to appear: 
<form name="it"> 
<div align="center"> 
<input onclick="copyit(this.form.select1)" type="button" value="Press to copy the highlighted text" name="btnCopy"> 
<p> 
<textarea name="select1" rows="4" cols="45"></textarea> 
</div> 
</form> 

回答

2
onclick="copyit(this.form.select1)" 

執行copyit()功能,並傳遞這是後來被命名爲的變量。傳遞的變量是this.form.select1,這是一個文本區域,ID爲select1,它與您點擊的輸入位置相同,因此爲this.form

至於爲什麼你的代碼不起作用 - 你應該在調整之前在這裏包含原始代碼。你可能刪除/改變了你不應該擁有的東西。

0

我不確定你在問什麼。你是否要求,當有人點擊任何按鈕/ div時,它會複製你想要的剪貼板文本?如果沒有,請忽略我的評論,如果是的話,我會解釋:

首先,用戶應該在哪裏點擊?

<a class="btn" CopydivFunction(#text)">CLICK ME TO Hello.</a> 

現在,添加JS功能。

function copyToClipboard(element) { 
    var $temp = $("<input>"); 
    $("body").append($temp); 
    $temp.val($(element).text()).select(); 
    document.execCommand("copy"); 
    $temp.remove(); 
} 

現在,把你希望有人複製(隱藏)文本:

<h1 id="text" class="hidden">some text. This part won't be seen because of the hidden class, and this is the text that will be copied to your clipboard.</h1> 

地顯示:在CSS無:我認爲你必須添加

#text{ 
display:none; 
} 

,所以沒有人看到它。 而且應該是這樣的,點擊<a>,你會得到h1#text的文字