【问题标题】:Copy div text content using javascript/jQuery使用 javascript/jQuery 复制 div 文本内容
【发布时间】:2017-10-09 02:49:52
【问题描述】:

这方面有很多帖子,但在花了几个小时尝试调整已经存在的解决方案后,我很清楚这有点复杂。

我正在尝试创建“复制到剪贴板”功能,以便我们的用户可以通过单击复制他们的序列号(我设法通过 2 种不同的解决方案实现了此功能),但有一个主要问题。

由于序列号是使用短代码动态生成的,因此我无法将其放在 HTML 'text'/'value' 字段中,如下所示:

<input id="serial" value="[shortcode here]">

因为这会破坏短代码,所以它必须放在它自己的 div 中,我这样做是这样的:

<div id="serial">[shortcode here]</div>

这会在页面上输出直接父 ID 为“serial”的短代码,因此我使用的 JS 应该从元素 ID - #serial 中选择文本。

不幸的是它没有......


我也尝试过采用这种方法,但没有成功:

来自 Roll Your Own 部分:https://www.sitepoint.com/javascript-copy-to-clipboard/

这个使用纯文本,但不使用短代码或自定义 div。


谁能为我提供如上例所示的不会破坏简码的有效剪贴板解决方案?

【问题讨论】:

  • 我认为可以将您的代码放在 HTML 输入元素中。您可以通过 jquery/javascript 轻松完成。之后,您可以应用复制文本的方法。
  • 发布你的 JS...

标签: javascript jquery html wordpress shortcode


【解决方案1】:

第二个@pruvik7373 回答

我认为 [shortcode] 可能包含一些可以转换为其他任何内容的代码,因此不要使用 textContent 使用 innerHTML 它会确保复制所有内容。

document.getElementById("copyButton").addEventListener("click", function() {
    copyToClipboardMsg(document.getElementById("copyTarget"), "msg");
});

document.getElementById("copyButton2").addEventListener("click", function() {
    copyToClipboardMsg(document.getElementById("serial"), "msg");
});

document.getElementById("pasteTarget").addEventListener("mousedown", function() {
    this.value = "";
});


function copyToClipboardMsg(elem, msgElem) {
	  var succeed = copyToClipboard(elem);
    var msg;
    if (!succeed) {
        msg = "Copy not supported or blocked.  Press Ctrl+c to copy."
    } else {
        msg = "Text copied to the clipboard."
    }
    if (typeof msgElem === "string") {
        msgElem = document.getElementById(msgElem);
    }
    msgElem.innerHTML = msg;
    setTimeout(function() {
        msgElem.innerHTML = "";
    }, 2000);
}

function copyToClipboard(elem) {
	  // create hidden text element, if it doesn't already exist
    var targetId = "_hiddenCopyText_";
    var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
    var origSelectionStart, origSelectionEnd;
    if (isInput) {
        // can just use the original source element for the selection and copy
        target = elem;
        origSelectionStart = elem.selectionStart;
        origSelectionEnd = elem.selectionEnd;
    } else {
        // must use a temporary form element for the selection and copy
        target = document.getElementById(targetId);
        if (!target) {
            var target = document.createElement("textarea");
            target.style.position = "absolute";
            target.style.left = "-9999px";
            target.style.top = "0";
            target.id = targetId;
            document.body.appendChild(target);
        }
        target.textContent = elem.innerHTML;
    }
    // select the content
    var currentFocus = document.activeElement;
    target.focus();
    target.setSelectionRange(0, target.value.length);
    
    // copy the selection
    var succeed;
    try {
    	  succeed = document.execCommand("copy");
    } catch(e) {
        succeed = false;
    }
    // restore original focus
    if (currentFocus && typeof currentFocus.focus === "function") {
        currentFocus.focus();
    }
    
    if (isInput) {
        // restore prior selection
        elem.setSelectionRange(origSelectionStart, origSelectionEnd);
    } else {
        // clear temporary content
        target.textContent = "";
    }
    return succeed;
}
<input id="copyTarget" value="Some initial text"> <button id="copyButton">Copy</button><br><br>
<div id="serial"><div>[pw_map address="New York City"</div> enablescrollwheel="false" key="YOUR API KEY"]</div> <button id="copyButton2">Copy</button><br><br>
<input id="pasteTarget"> Click in this Field and hit Ctrl+V to see what is on clipboard<br><br>
<span id="msg"></span><br>

【讨论】:

    【解决方案2】:

    你可以这样做:

     <div id="serial">[shortcode here]</div>
     <input id="some_other_id" type="text" />
    

    还有 javascript 代码:

                 //first get text from your div and put it inside input field
                 //then apply code to copy that text from input field
                 $(document).ready(function(){
                     var text = $("#serial").text();
                     $("#some_other_id").val(text);
                       //your code for copying text from input field goes here
                 });
    

    【讨论】:

      【解决方案3】:

      下面的代码对我有用。

      注意: 下面的 sn-p 可能无法工作,因为 window 对象不可访问。

      $(function() {
        $('#serial').click(function() {
          window.clipboardData.setData('text', $(this).text());
        });
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <div id="serial">[shortcode here]</div>

      【讨论】:

        【解决方案4】:

        document.getElementById("copyButton").addEventListener("click", function() {
            copyToClipboardMsg(document.getElementById("copyTarget"), "msg");
        });
        
        document.getElementById("copyButton2").addEventListener("click", function() {
            copyToClipboardMsg(document.getElementById("copyTarget2"), "msg");
        });
        
        document.getElementById("pasteTarget").addEventListener("mousedown", function() {
            this.value = "";
        });
        
        
        function copyToClipboardMsg(elem, msgElem) {
        	  var succeed = copyToClipboard(elem);
            var msg;
            if (!succeed) {
                msg = "Copy not supported or blocked.  Press Ctrl+c to copy."
            } else {
                msg = "Text copied to the clipboard."
            }
            if (typeof msgElem === "string") {
                msgElem = document.getElementById(msgElem);
            }
            msgElem.innerHTML = msg;
            setTimeout(function() {
                msgElem.innerHTML = "";
            }, 2000);
        }
        
        function copyToClipboard(elem) {
        	  // create hidden text element, if it doesn't already exist
            var targetId = "_hiddenCopyText_";
            var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
            var origSelectionStart, origSelectionEnd;
            if (isInput) {
                // can just use the original source element for the selection and copy
                target = elem;
                origSelectionStart = elem.selectionStart;
                origSelectionEnd = elem.selectionEnd;
            } else {
                // must use a temporary form element for the selection and copy
                target = document.getElementById(targetId);
                if (!target) {
                    var target = document.createElement("textarea");
                    target.style.position = "absolute";
                    target.style.left = "-9999px";
                    target.style.top = "0";
                    target.id = targetId;
                    document.body.appendChild(target);
                }
                target.textContent = elem.textContent;
            }
            // select the content
            var currentFocus = document.activeElement;
            target.focus();
            target.setSelectionRange(0, target.value.length);
            
            // copy the selection
            var succeed;
            try {
            	  succeed = document.execCommand("copy");
            } catch(e) {
                succeed = false;
            }
            // restore original focus
            if (currentFocus && typeof currentFocus.focus === "function") {
                currentFocus.focus();
            }
            
            if (isInput) {
                // restore prior selection
                elem.setSelectionRange(origSelectionStart, origSelectionEnd);
            } else {
                // clear temporary content
                target.textContent = "";
            }
            return succeed;
        }
        <input id="copyTarget" value="Some initial text"> <button id="copyButton">Copy</button><br><br>
        <span id="copyTarget2">Some Other Text</span> <button id="copyButton2">Copy</button><br><br>
        <input id="pasteTarget"> Click in this Field and hit Ctrl+V to see what is on clipboard<br><br>
        <span id="msg"></span><br>

        请你试试上面的 sn-p 吗?

        【讨论】:

        • @puvik7373 是的! - 只需很少的适应就可以完美地工作,谢谢!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-05
        • 1970-01-01
        • 2014-11-24
        • 1970-01-01
        • 2022-07-05
        • 1970-01-01
        • 2012-02-09
        相关资源
        最近更新 更多