Как я могу назначить переменную в html и скопировать ее значение в буфер обмена - PullRequest
0 голосов
/ 31 марта 2020

У меня есть рабочий код, в который я копирую значение, вставляя его в текстовое поле 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 = "";
}

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

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>

SCRIPT:

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 {
        // ...
    }
}

1 Ответ

0 голосов
/ 31 марта 2020

Не могли бы вы попробовать использовать следующую функцию 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 исходный код [ТЕСТ-код].

image

Снимок экрана

Надеюсь, это будет полезно. Спасибо

...