最近項目中需要實現功能:點擊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">