JS document.execCommand實現復制功能(帶你出坑)


轉自 : https://www.cnblogs.com/minigrasshopper/p/8967339.html

<script type="text/javascript">
    function gocopy_copy() {
     
        let input = document.querySelector('#demoInput');
        //alert(input);
       let data =  input.select();
      // alert(data);
           //document.execCommand('gocopy_copy') 
           document.execCommand('copy');
            
            //  location.href="weixin://";
            // window.open('weixin://',"_blank");  
            // alert('復制成功,准備跳轉到微信');
            alert("微信號復制成功,現在進入微信添加好友"); 
         window.location.href='weixin://';
           
        
        
    }
 
</script>


<div style="position: fixed;left:0 ;bottom: 0px;width: 100%;height: 70px;line-height:50px;padding: 5px 5px 5px 5px;font-size: 16px;background-color: #fff;
    border-top: 1px solid #ccc;    max-width: 740px;z-index:9999;" onclick="gocopy_copy()">
    <div style="width: 15%;float: left;"><img src="http://v1.cdn-static.cn/2020/6/9/62063_kb6petyo.png?imageView2/2/w/1400" style="width: 50px"></div>
    <div style="width: 45%;float: left;line-height:25px;"><p>微信:<span style="    font-size: 16px;
    background-color: #ffff00;
    color: #ff0000;
    padding: 0px 2px;font-weight: bold;
}">zxr876</span></p><p>(歡迎您前來咨詢)</p></div>
    <div  class="copy" style="margin-top:5px;"><img  class="tcpyq" src="http://v1.cdn-static.cn/2020/6/9/62063_kb6pety1.png?imageView2/0/w/390" style="width: 120px;"></div>
</div>

<input id="demoInput" value="zxr876" type="text" style='opacity: 0;position: absolute;' >

 

------------------------------------------------------------------------------------------------------------

最近項目中需要實現功能:點擊button,復制input框的值;

我使用的是 document.execCommand('copy')的方法;

但是很郁悶的是,始終實現不了功能;代碼如下

HTML代碼

(v-model是vue框架中的雙向數據綁定,不懂的請移步vue文檔)

<input id='input_url' v-model='product_url' disabled type="text">

JS代碼

var input = $('#input_url');
input.select();
document.execCommand("Copy");

然后就郁悶了,就這么幾行代碼,為啥不行呢?JS和網上寫的一模一樣啊??

現在來解釋為啥失敗,踩了幾個小時的坑

不能實現的原因:

  • input框不能有disabled屬性
  • 根據第一條擴展,input的width || height 不能為0;
  • input框不能有hidden屬性

意思就是,input框要在正常的編輯狀態下,暫且這么解釋吧;

解決方案:

因為業務邏輯上input框確實不能編輯,所以disabled屬性是必須要的;

那我用另一個input框展示相同的數據,然后設置opacity=0;這樣就不可見了;(注意這里用hidden也是不行的)

但是新增的input還是占有空間,所以再來個粗暴的樣式 position: absolute;這樣就脫離了文檔流;

JS代碼不變,修改HTML如下:

 

<input id='input_url' v-model='product_url' style='opacity: 0;position: absolute;' type="text">
<input v-model='product_url' disabled type="text">

 

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

 

 轉自 :https://www.cnblogs.com/minigrasshopper/p/8967339.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM