首页 > 解决方案 > 如何在 html 中分配变量并将其值复制到剪贴板

问题描述

我有工作代码,我通过将值插入到 html 文本框中来复制值,我目前的过程是

1-将图像 url 保存到 php 变量 $url 2-然后将 $url 回显到 html 文本框然后 3-将其复制到用户的剪贴板

我只想删除我的第二步,并希望以任何其他方式将其复制到剪贴板

我想将我的一个上传图像链接的值复制到用户剪贴板,方法是先将其保存到一个 php 变量,然后回显到 html 文本框。

但是我在通过 html 文本框复制它时遇到问题,所以我想将它保存到 html 中的变量,然后将其复制到用户的剪贴板。

这里有人可以提出一种工作方法吗?这是我的工作代码:

PHP:

//upload.php
if($_FILES["file"]["name"] != '')
    {
        $test = explode('.', $_FILES["file"]["name"]);
        $ext = end($test);
        $name = rand(100, 999999999) . '.' . $ext;
        $location = './upload/' . $name; 
        $url= 'www.chat.com/upload/' . $name;

        move_uploaded_file($_FILES["file"]["tmp_name"], $location);
    // echo '<img src="'.$location.'" height="150" width="225" class="img-thumbnail" />';

    // echo "\n\n\n\n$url";
} else {
    $url = "";
}

风格:

.button {
    background-color: #4CAF50;
    border: none;
    color: white;
    padding: 55px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 15px 2px;
    cursor: pointer;
}

HTML:

<input   type="text" value="<?php echo $url; ?>" id="myInput">

<button onclick="myFunction()">
    <h4 style="color:green;font-size:15px;"> 
        <b>Copy Img link</b>
    </h4>
</button>

脚本:

function myFunction() {
    let inputEl = document.getElementById("myInput");
    inputEl.select();                                    // Select element
    inputEl.setSelectionRange(0, inputEl.value.length); // select from 0 to element length

    const successful = document.execCommand('copy');   // copy input value, and store success if needed

    if(successful) {

        //  alert("Copied IMAGE  URL PASTE IT TO SENDER : " + inputEl.value);
    } else {
        // ...
    }
}

标签: phphtmlvariablescopyclipboard

解决方案


你能尝试使用下面的 JS 函数吗?

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;
}

你可以像下面这样使用这个函数:

copyToClipboard(yourImageLink);

或者

copyToClipboard('<?php echo $url; ?>');

这是一个完整的PHP源代码[测试代码]。

<?php
//upload.php
if (isset($_FILES["file"]["name"]) && $_FILES["file"]["name"] != '') {
    /*$test = explode('.', $_FILES["file"]["name"]);
    $ext = end($test);
    $name = rand(100, 999999999) . '.' . $ext;
    $location = './upload/' . $name;
    $url = 'www.chat.com/upload/' . $name;

    move_uploaded_file($_FILES["file"]["tmp_name"], $location);
    // echo '<img src="'.$location.'" height="150" width="225" class="img-thumbnail" />';
    // echo "\n\n\n\n$url";
    */

    $test = explode('.', $_FILES["file"]["name"]);
    $ext = end($test);
    $name = rand(100, 999999999) . '.' . $ext;
    $location = './' . $name;
    $url = 'http://localhost/' . $name;

    move_uploaded_file($_FILES["file"]["tmp_name"], $location);
} else {
    $url = "";
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Copy & Paste YOUR IMAGE LINK </title>
    <style>
        .button {
            background-color: #4CAF50;
            border: none;
            color: white;
            padding: 55px 32px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 15px 2px;
            cursor: pointer;
        }
    </style>
</head>

<body >
<form method="post" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <button type="submit">Upload</button>

    <button type="button" onclick="myFunction()"><h4 style="color:green;font-size:15px;"><b>Copy Img link</b></h4></button>
</form>

<input style="width: 1px; height: 1px; opacity: 0;" type="text" value="<?php echo $url; ?>" id="myInput">

<script>
    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;
    }

    function myFunction() {
        let ele = document.getElementById('myInput');
        const successful = copyToClipboard(ele);
        if (successful) {
            alert("Copied IMAGE  URL PASTE IT TO SENDER : " + ele.value);
        } else {
            // ...
        }
    }


</script>
</body>
</html>


截屏

我希望它会有所帮助。谢谢


推荐阅读