前端JS複製特定區域的文本(兼容safari)

html5的webAPI接口能夠很輕鬆的使用短短的幾行代碼就實現點擊按鈕複製區域文本的功能,不須要依賴flash。javascript

代碼以下:css

/* 建立range對象 */ const range = document.createRange(); range.selectNode(element); // 設定range包含的節點對象 

/* 窗口的selection對象,表示用戶選擇的文本 */ const selection = window.getSelection(); if(selection.rangeCount > 0) selection.removeAllRanges(); // 將已經包含的已選擇的對象清除掉
selection.addRange(range);                                // 將要複製的區域的range對象添加到selection對象中
 document.execCommand('copy'); // 執行copy命令,copy用戶選擇的文本

 

 
//兼容Pc端的safari瀏覽器
let node = document.getElementById('copy');//input框
      node.setAttribute('value', 'hello world');
    let issafariBrowser = /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent);
    if(issafariBrowser){
      //safari瀏覽器單獨處理
      node.setSelectionRange(0, 9999);
    }
    else{
     //其餘瀏覽器
      const range = document.createRange();
      range.selectNode(node);
      const selection = window.getSelection();
      if(selection.rangeCount > 0) selection.removeAllRanges();
      selection.addRange(range);
    }
    
    document.execCommand('copy');

  還有一種兼容safari和chrome瀏覽器的通用寫法不須要判斷,這種寫法在demo中能夠成功。html

  demo以下:html5

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
  <style>
    .btn{
      cursor: pointer;
      width: 200px;
      height: 100px;
      background: red;
      display: inline-block;
    }
  </style>
	<!-- <link type="text/css" rel="styleSheet" href="1.css"> -->
</head>
<body style="background: blue">
	<div class="div1">
    
  </div>
  <div id="cardList">
        <div class="btn" id='btn'>點擊我,複製我</div>
      <input  id='copy'/>
  </div>
  
</body>
	
    
            
   
    <script>
      var btn = document.querySelector('#btn');
      btn.addEventListener('click',function(){


         
          let input = document.getElementById('copy');

          input.setAttribute('readonly', 'readonly');
          input.setAttribute('value', 'hello world');
          


          const range = document.createRange();
          
          range.selectNode(input);
          const selection = window.getSelection();
          console.log(selection)
          if(selection.rangeCount > 0) selection.removeAllRanges();
          selection.addRange(range);
          document.execCommand('copy');
      })
    </script>

</html>

  

可是在react項目中,在safari瀏覽器中
window.getSelection();對象的anchorNode值一直爲null,
因此在safari中不成功,
因此最終採用了判斷是否爲safari瀏覽器來進行不一樣操做的方法。
API參考:
相關文章
相關標籤/搜索