如何使用JavaScript在前节点/块中选择文本? [英] How can I use JavaScript to select text in a pre node/block?
问题描述
我理解不允许JS将任意文本复制到剪贴板的安全原因,但是有一种方法可以通过单击按钮来选择预先节点中的文本,类似于select()函数在输入中的工作方式?
I understand the security reasons behind dis-allowing JS copying arbitrary text to the clipboard, but is there a method by which clicking a button can select the text in a pre node similar to how the select() function works in an input?
我不是在寻找复制到剪贴板的jQuery插件。我只想在pre block中发短信以便突出显示,以便用户可以ctrl-c进行复制。
I am not looking for the jQuery plugin that copies to clipboard. I just want to text in pre block to be highlighted so user can ctrl-c to copy.
我好像找到了深蹲。
推荐答案
也许你可以将 pre
标签更改为 textarea
用户点击时标记:
Maybe you could change the pre
tag into a textarea
tag when the user clicks on it:
jsFiddle: http://jsfiddle.net/WzBQf/
jsFiddle: http://jsfiddle.net/WzBQf/
<button id="btnSelect">Select!</button>
<button id="btnDeselect">Deselect!</button>
<hr />
<div id="text">
<pre id="txt1">Test</pre>
<textarea id="txt2" readonly="readonly"></textare>
</div>
以及JavaScript(jQuery)代码:
And the JavaScript (jQuery) code:
$("#txt1, #btnSelect").click(function() {
Select();
});
function Select() {
$("#txt2").val($("#txt1").html()).show();
$("#txt1").hide();
$("#txt2").focus()[0].select();
}
function Deselect() {
$("#txt1").html($("#txt2").val()).show();
$("#txt2").hide();
}
$("#txt2").blur(function() {
Deselect();
});
$("#btnDeselect").click(function() {
Deselect();
});
这篇关于如何使用JavaScript在前节点/块中选择文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!