创建一个"复制按钮"

时间:2017-02-08 19:33:20

标签: javascript jquery html

好吧,当我在互联网上搜索一些基本代码进行检查时 - 我找到了这个。应该复制所选文本的简单代码。由于我是JS的一个完整的新手,我检查了我不理解的方法的含义 - 并重新编写代码,因为我做了一些调整。

仍然代码不起作用,如果有人可以解释 - 这部分"" copyit(this.form.select1)"" - 即使我有点理解"这个" - 我无法理解这里有什么作用

function copyit(theField) {
var selectedText = document.getSelection();
if (selectedText.type == 'Text') {
  var newRange = selectedText.createRange();
  theField.focus();
  theField.value = newRange.text;
} else {
  alert('select a text in the page and then press this button');
}
}
</script>



<form name="it">
<div align="center">
<input onclick="copyit(this.form.select1)" type="button" value="Press to copy the highlighted text" name="btnCopy">
<p>
<textarea name="select1" rows="4" cols="45"></textarea>
</div>
</form>

这是原始代码 - 它无法正常工作

<SCRIPT LANGUAGE="JavaScript">
function copyit(theField) {
var selectedText = document.selection;
if (selectedText.type == 'Text') {
  var newRange = selectedText.createRange();
  theField.focus();
  theField.value = newRange.text;
} else {
  alert('select a text in the page and then press this button');
}
}
</script>


And in the body of your web page, add the following where you want the text to appear:
<form name="it">
<div align="center">
<input onclick="copyit(this.form.select1)" type="button" value="Press to copy the highlighted text" name="btnCopy">
<p>
<textarea name="select1" rows="4" cols="45"></textarea>
</div>
</form>

2 个答案:

答案 0 :(得分:2)

onclick="copyit(this.form.select1)"

执行copyit()函数并传递一个稍后命名为theField的变量。传递的变量是this.form.select1,它是ID为select1的textarea,其格式与您点击的输入相同,因此this.form

至于为什么你的代码不起作用 - 你应该在调整之前在这里包含原始代码。您可能删除/更改了您不应该拥有的内容。

答案 1 :(得分:0)

我不确定你在问什么。您是否要求,当有人点击任何按钮/ div时,它会复制您想要的剪贴板文本?如果不是,请忽略我的评论,如果是,我会解释:

首先,用户应该在哪里点击?

foo-gen

现在,使用JS添加该功能。

foo-use

现在,放置您想要复制的文本(隐藏它):

<a class="btn" CopydivFunction(#text)">CLICK ME TO Hello.</a>

在css上放置显示:无:

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}

我认为你必须补充一点,所以没有人看到它。 应该是这样,点击<h1 id="text" class="hidden">some text. This part won't be seen because of the hidden class, and this is the text that will be copied to your clipboard.</h1> 即可获得#text{ display:none; }

中的文字