html怎么实现按钮复制内容,如下图

html-css05

html怎么实现按钮复制内容,如下图,第1张

要用js实现

      var clipboard = function (window, document, navigator) {

          var textArea, copy

          function isOS() {

              return navigator.userAgent.match(/ipad|iphone/i)

          }

          function createTextArea(text) {

              textArea = document.createElement('textArea')

              textArea.value = text

              document.body.appendChild(textArea)

          }

          function selectText() {

              var range, selection

              if (isOS()) {

                  range = document.createRange()

                  range.selectNodeContents(textArea)

                  selection = window.getSelection()

                  selection.removeAllRanges()

                  selection.addRange(range)

                  textArea.setSelectionRange(0, 999999)

              } else {

                  textArea.select()

              }

          }

          function copyToClipboard() {

              document.execCommand('copy')

              document.body.removeChild(textArea)

          }

          copy = function copy(text) {

              createTextArea(text)

              selectText()

              copyToClipboard()

          }

          return {

              copy: copy

          }

      }(window, document, navigator)

用法:

clipboard.copy('222')

给按钮添加一个单击属性 <button onclick="copy">点我复制P 里面的内容</button>

比如要复制的是p标签的文字 <p id="p">123</p>           <p id="p2">456</p>

<!DOCTYPE html>

<html>

<head>

    <title>复制内容</title>

    <script>

        function copy(){

            var a = document.getElementById("p").innerText//获取P字段里面的内容。

            document.getElementById("p2").innerText = a  //把p字段里的内容赋予到id为P2的标签里

        }

    </script>

</head>

<body>

    <button onclick="copy()">点我复制P 里面的内容</button>

    <p id="p">123</p>           <p id="p2">456</p>

</body>

</html>

/1、网页代码如下:

<script language=javascript>

   // 自动 COPY 代码开始

   function MM_findObj(n, d) { //v4.0

   var p,i,x if(!d) d=document if((p=n.indexOf("?"))>0&&parent.frames.length) {

   d=parent.frames[n.substring(p+1)].document n=n.substring(0,p)}

   if(!(x=d[n])&&d.all) x=d.all[n] for (i=0!x&&i<d.forms.lengthi++) x=d.forms[n]

   for(i=0!x&&d.layers&&i<d.layers.lengthi++) x=MM_findObj(n,d.layers.document)

   if(!x && document.getElementById) x=document.getElementById(n) return x

   }

   function JM_cc(ob){

   var obj=MM_findObj(ob) if (obj) {

   obj.select()js=obj.createTextRange()js.execCommand("Copy")}

   alert("复制成功!您可以将本页推荐给您QQ或者论坛上的朋友阅读!")

   }

   

   // 自动 COPY 代码结束

   document.write('<br><b><font color=red style=font-size:14px>点击复制推荐给您的朋友阅读:</font></b><input name="page_url" value="'+window.location.href+'" size="64" style=color:red value="点击复制地址给您的朋友阅读" onClick=JM_cc("page_url")>')

   </script>

2、复制的HTML代码的话,可以在代码前加上<span>,在代码后加上</span>。例:<span>这里是你复制的内容!!</span>。