剪切板和上傳文件內容獲取

1.獲取剪切板內容

場景:在粘貼時將粘貼內容按換行粘貼到不同輸入框,類似粘貼註冊碼之類的多個輸入框一次粘貼功能。

主要技術:input元素onpaste方法,入參是event,也可以直接獲取event,內容在event.clipboardData中,items屬性可以看具體內容對象,使用getData("text")方法可以獲取到內容,參數還可以是Text,text/plain等。

擴展:富文本,contenteditable=true;document.createRange(),window.getSelection(),selection.removeAllRangs(),range.selectNodeContents(元素),selection.addRange(range)。另外還有一個最主要是,document.execCommand('copy')、粘貼、加粗等等,是富文本的關鍵功能。

2.獲取上傳文件內容

上傳文件內容首先是通過input的onchange方法獲取,裏邊有files對象列表,但是這裏只能看到文件大小、格式等信息,要看文件內容,則要藉助FileReader對象(需要注意兼容性),使用FileReader實例化對象的readAsText方法來讀取文件內容,參數是前邊的files單個對象,讀取後可使用onload接收,內容在result中

 1 <input type="file" onchange="upload(this)" />  
 2 
 3 function upload(input) {  //支持chrome IE10  
 4     if (window.FileReader) {  
 5         var file = input.files[0];  
 6         filename = file.name.split(".")[0];  
 7         var reader = new FileReader();  
 8         reader.onload = function() {  
 9             console.log(this.result)  
10             alert(this.result);  
11         }  
12         reader.readAsText(file);  
13     }   
14     //支持IE 7 8 9 10  
15     else if (typeof window.ActiveXObject != 'undefined'){  
16         var xmlDoc;   
17         xmlDoc = new ActiveXObject("Microsoft.XMLDOM");   
18         xmlDoc.async = false;   
19         xmlDoc.load(input.value);   
20         alert(xmlDoc.xml);   
21     }   
22     //支持FF  
23     else if (document.implementation && document.implementation.createDocument) {   
24         var xmlDoc;   
25         xmlDoc = document.implementation.createDocument("", "", null);   
26         xmlDoc.async = false;   
27         xmlDoc.load(input.value);   
28         alert(xmlDoc.xml);  
29     } else {   
30         alert('error');   
31     }   
32 }  

 

 

的readAsText方法來讀取文件內容,參數是前邊的files單個對象,讀取後可使用onload接收,內容在result中

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章