我有三个包含唯一 URL 的文本框和按钮。单击复制按钮时,它应该复制特定的文本框值,我需要绑定(bind) Ctrl+v 和鼠标右键单击并通过 jQuery 或 javascript 函数粘贴事件。
当我将光标放在浏览器地址栏中时,当我使用 Ctrl+v 或 right click and paste go
事件时,它应该粘贴从文本框中复制的 url 并转到特定的 URL。
那么如何在单击复制按钮后在 jQuery/javascript 中绑定(bind)粘贴事件?
最佳答案
检查这个FIDDLE关于如何在输入和文本区域中执行此操作。支持鼠标和键盘事件。
HTML:
<p>
<input class="js-copytextinput" value="http://www.stackoverflow.com"></input>
<button class="js-textinputcopybtn">Copy Text Input</button>
</p>
<p>
<textarea class="js-copytextarea">http://www.stackexchange.com</textarea>
<button class="js-textareacopybtn">Copy Textarea</button>
</p>
JS:
//textinput copy
var copyTextinputBtn = document.querySelector('.js-textinputcopybtn');
copyTextinputBtn.addEventListener('click', function(event) {
var copyTextinput = document.querySelector('.js-copytextinput');
copyTextinput.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text input command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
});
来源:Snippet from the answer provided by Dean Taylor with little modifications
你可以像这样在jQuery中绑定(bind)复制粘贴和剪切事件,
$(".select").bind({
copy : function(){
$('span').text('copy behaviour detected!');
},
paste : function(){
$('span').text('paste behaviour detected!');
},
cut : function(){
$('span').text('cut behaviour detected!');
}
});
检查这个Fiddle关于通过 jQuery 绑定(bind)复制、剪切和粘贴事件。
- 在剪切、复制和粘贴中绑定(bind)了键和鼠标事件。
$(document).ready(function() {
//textinput copy
var copyTextinputBtn = document.querySelector('.js-textinputcopybtn');
copyTextinputBtn.addEventListener('click', function(event) {
var copyTextinput = document.querySelector('.js-copytextinput');
copyTextinput.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text input command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
});
//textarea copy
var copyTextareaBtn = document.querySelector('.js-textareacopybtn');
copyTextareaBtn.addEventListener('click', function(event) {
var copyTextarea = document.querySelector('.js-copytextarea');
copyTextarea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text area command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
});
});
http://www.stackoverflow.comhttp://www.stackexchange.comhttp://www.stackoverflow.comhttp://www.stackexchange.com
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<input class="js-copytextinput" value="http://www.stackoverflow.com"></input>
<button class="js-textinputcopybtn">Copy Text Input</button>
</p>
<p>
<textarea class="js-copytextarea">http://www.stackexchange.com</textarea>
<button class="js-textareacopybtn">Copy Textarea</button>
</p>
希望这有帮助..
关于javascript - 如何绑定(bind)键盘和鼠标的粘贴事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15757636/