首页 > 解决方案 > 复制另一个元素的源代码

问题描述

我想做一个网站,我可以放一些按钮、卡片设计、图像等......当我点击该材料下方的按钮时,我想复制该材料的源代码。该项目旨在更快地访问我在编码时使用的材料,并更快地完成项目。

虽然我想了一会儿,但我没有找到我应该使用哪种方法。而且如果我以后想让项目变得更复杂,我不想成为我之前使用的错误方法的受害者。如果你能帮我解决这个问题,我会很高兴。简而言之,我想要一个在单击时复制上面“div”的源代码的按钮。

我不是母语人士,所以如果我犯了任何语法错误或不完整的句子,我很抱歉。

谢谢你。

标签: javascripthtml

解决方案


要复制一个元素的源代码,使用输入比较简单。

1)获取元素outerHtml,其文本从其开始标签到结束标签。

var elemenSourceCode = ele.outerHTML;

2)我们需要一个输入,这个输入可以隐藏在文档中,因为一个就足够了,或者我们可以在js中创建一个,将它添加到文档中使用它,然后删除它。

var input = document.createElement('input');

3)我们将元素outerHTML设置为输入的值。

input.value = elemenSourceCode;

4)这里我们将输入附加到文档中,就像前面的 i 侧一样,如果您在文档中隐藏了一个,则可以跳过它。

document.body.appendChild(input); 

5)我们调用select()输入来执行用户喜欢的选择。

input.select();

6)由于文档中有一些文本被选中,我们调用document.execCommand("copy")来复制选中的文本。

document.execCommand("copy");

7) 现在文本被复制到我们的剪贴板,所以我们不再需要输入了。

document.body.removeChild(input);

下面的例子

document.querySelector('.copy').onclick = () => {
  var button = document.querySelector('.Buttondesign');
  CopyElementSourceCode(button);
};

function CopyElementSourceCode(ele) {
  var elemenSourceCode = ele.outerHTML;
  var input = document.createElement('input');
  input.value = elemenSourceCode;
  document.body.appendChild(input);
  input.select();
  document.execCommand("copy");
  document.body.removeChild(input);
}
/* just for reference */

textarea {
  width: 400px;
  height: 100px;
}
<p><button class="Buttondesign">Button</button></p>
<p><button class="copy">Copy</button></p>
<p><textarea placeholder="try pasting here"></textarea></p>

隐藏输入示例

document.querySelector('.copy').onclick = () => {
  var button = document.querySelector('.Buttondesign');
  CopyElementSourceCode(button);
};

function CopyElementSourceCode(ele) {
  var elemenSourceCode = ele.outerHTML;
  var input = document.querySelector('#copyTool')
  input.value = elemenSourceCode;
  input.select();
  document.execCommand("copy");
}
/* just for reference */

textarea {
  width: 400px;
  height: 100px;
}
<p><button class="Buttondesign">Button Design To Copy</button></p>
<p><button class="copy">Copy</button></p>
<p><textarea placeholder="try pasting here"></textarea></p>



<!-- it has to be somewhat in there, we can't just use display:none; and that will prevent user select like to happen therefore no copying, i mean you can't select what you can't event see, i'm sure there's a lot of ways to hide the input in the doucument -->
<input type="text" style="position:absolute;width:1px;height:0;padding:0;border:none;" id="copyTool">


推荐阅读